如何在点击时更改JButton的背景颜色

huangapple go评论93阅读模式
英文:

How to change the background color of a Jbutton on click

问题

以下是您提供的代码的翻译部分:

我正在尝试在单击按钮时更改JButton的颜色但实际上出现了蓝色的颜色而不是我所描述的颜色

**目标**目标是在单击按钮时更改颜色

我进行了几次搜索但每次都出现了蓝色的颜色

我尝试了重写`paintComponent`,以及`this.getModel`等多种替代方法但都没有奏效

我的按钮类

// 在这里是您的TButton类的代码,由于篇幅较长,这里省略了具体内容。

主菜单面板

// 在这里是您的主菜单面板的代码,由于篇幅较长,这里省略了具体内容。

然后是一些图像
[我的错误][1]

  [1]: https://i.stack.imgur.com/gz3hp.png

如果您需要关于代码的进一步解释或指导,请随时提问。

英文:

I'm trying to change the color of a JButton when you click on it, but a blue color appears instead of the one I wrote about.

Goal: The goal is that when you click on the button the color change

I did several searches, but each time a blue font appeared.

I tried overide paintComponent, several alternatives such as this.getModel, but nothing works.

My button class:

package com.tralamy.lancherX.display;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class TButton extends JButton {

    private Color hoverColor = Display.LIGHT_GRAY;
    private Color pressColor = Display.LIGHT_DARK;
    private Color firstColor;
    private Color basic;

    private MouseAdapter hoverAdapter = new MouseAdapter() {
        @Override
        public void mouseEntered(MouseEvent e) {
            basic = firstColor;
            TButton.this.setBackground(hoverColor);
        }

        @Override
        public void mouseExited(MouseEvent e) {
            TButton.this.setBackground(basic);
        }
    };

    private MouseAdapter pressAdapter = new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
            TButton.this.setBackground(pressColor);
            super.mousePressed(e);
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            TButton.this.setBackground(basic);
            super.mouseReleased(e);
        }
    };

    public TButton (String text){
        super(text);
        init();
    }

    public TButton (Icon icon){
        super(icon);
        init();
    }

    public TButton (){
        super();
        init();
    }

    private void init()
    {
        firstColor = this.getBackground();
        setBorder(null);
        setBorderPainted(false);
        setContentAreaFilled(false);
        setOpaque(false);
        setFocusPainted(false);
        setPressedIcon(new ImageIcon());
    }

    @Override
    public void setBackground(Color bg) {
        super.setBackground(bg);
        firstColor = bg;
    }

    public void setHover()
    {
        this.addMouseListener(hoverAdapter);
    }

    public void removeHover()
    {
        this.removeMouseListener(hoverAdapter);
    }

    public void setPress()
    {
        this.addMouseListener(pressAdapter);
    }

    public void removePress()
    {
        this.removeMouseListener(pressAdapter);
    }

    public void setHoverColor(Color color)
    {
        hoverColor = color;
    }

    public Color getHoverColor()
    {
        return hoverColor;
    }

    public Color getPressColor() {
        return pressColor;
    }

    public void setPressColor(Color pressColor) {
        this.pressColor = pressColor;
    }
}

Main menu panel:

private JPanel menuPanel() {
        mp = new JPanel();
        setPercentWidth(mp, 25);

        mp.setBackground(LIGHT_GRAY);
        mp.setLayout(new BorderLayout());

        JPanel userSection = new JPanel();
        userSection.setLayout(new GridBagLayout());

        setPercentHeight(userSection, 5);
        userSection.setPreferredSize(new Dimension(userSection.getWidth(), 0));
        userSection.setBackground(LIGHT_DARK);

        userIconButton.setHorizontalAlignment(SwingConstants.CENTER);
        userName.setHorizontalAlignment(SwingConstants.CENTER);
        userIconButton.setBorder(new EmptyBorder(0,0,0,10));

        userSection.add(userIconButton);
        userSection.add(userName);

        menuButtons.add(new TButton("Library"));
        menuButtons.add(new TButton("Store"));
        menuButtons.add(new TButton("Friends"));
        menuButtons.add(new TButton("News"));


        JPanel menuSection = new JPanel();
        menuSection.setLayout(new BoxLayout(menuSection, BoxLayout.Y_AXIS));
        menuSection.setOpaque(false);

        for (TButton button : menuButtons) {
            button.setAlignmentX(TButton.CENTER_ALIGNMENT);

            button.setFont(App.setSemiBoldNunito(48));

            button.setForeground(SUPER_SUPER_LIGHT_GRAY);

            button.setBackground(SUPER_LIGHT_GRAY);

            button.setBorder(null);
            button.setBorderPainted(true);
            button.setContentAreaFilled(true);
            button.setOpaque(true);

            button.setHoverColor(DARK_GRAY);
            button.setHover();

            button.setPressColor(LIGHT_DARK);
            button.setPress();

            TButton marginLabel = new TButton();

            marginLabel.setSize(MAIN_MENU_MARGIN, MAIN_MENU_MARGIN);
            marginLabel.setMaximumSize(new Dimension(MAIN_MENU_MARGIN, MAIN_MENU_MARGIN));
            marginLabel.setMinimumSize(new Dimension(MAIN_MENU_MARGIN, MAIN_MENU_MARGIN));

            setPercentWidth(button, 20);

            menuSection.add(marginLabel);
            
            menuSection.add(button);

        }

        mp.add(menuSection);
        mp.add(userSection, BorderLayout.SOUTH);
        return mp;
    }

And then some image:
My bug

And thank you in advance

答案1

得分: 1

如果您想在用户单击按钮时更改按钮的背景颜色并使其保持不变,那么可以在按钮上使用setContentAreaFilled(false)。然后需要将不透明属性重置为true,因为根据setContentAreaFilled的文档:“此函数可能会导致组件的不透明属性更改”,例如:

import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class MainPersist {
    
    private static void createAndShowGUI() {
        final JButton button = new JButton("Click to change color");
        button.addActionListener(e -> {
            button.setContentAreaFilled(false);
            button.setOpaque(true); //重置不透明度
            button.setBackground(Color.CYAN.darker()); //将所需颜色设置为背景
        });
        
        final JFrame frame = new JFrame("Button bg on click");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(button);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
    
    public static void main(final String[] args) {
        SwingUtilities.invokeLater(MainPersist::createAndShowGUI);
    }
}

否则,如果您只想在单击按钮时更改按钮的颜色,然后在释放时恢复正常,那么请查看这个问题,它正好涉及到这个。截至我发布这个答案的时间,它还没有被接受的答案(作为最近的问题),但至少有一个/我的答案(建议修改按钮的ButtonUI),我猜应该会有更多的答案出现。

英文:

If you want to change the background of the button with a persistent color when the user clicks on the button, then you can use setContentAreaFilled(false) on it. Then it is required to reset the opaque property to true because according to the docs of setContentAreaFilled: "This function may cause the component's opaque property to change.", for example:

import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class MainPersist {
    
    private static void createAndShowGUI() {
        final JButton button = new JButton("Click to change color");
        button.addActionListener(e -> {
            button.setContentAreaFilled(false);
            button.setOpaque(true); //Reset the opacity.
            button.setBackground(Color.CYAN.darker()); //Set your desired color as the background.
        });
        
        final JFrame frame = new JFrame("Button bg on click");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(button);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
    
    public static void main(final String[] args) {
        SwingUtilities.invokeLater(MainPersist::createAndShowGUI);
    }
}

Otherwise, if you want the button to only change its color when clicked and then return back to normal when released, then take a look at this question which is about exactly that. It has no accepted answers yet (it is very recent as of the time this answer itself is posted), but there is at least one/my answer (which suggests to modify the ButtonUI of the button) and there should be more answers coming I guess.

huangapple
  • 本文由 发表于 2020年8月17日 03:25:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/63441096.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定