首页 > 解决方案 > 如何更改按钮的颜色?

问题描述

在我的程序中,我有 2 个按钮:第一个更改框架背景,第二个更改按钮背景(仅用于自身)。关键是程序应该改变程序中每个按钮的按钮背景(不仅是它自己)。我应该如何重写对话框

class ButtonBackgroundChange implements ActionListener{
    private JDialog dialog;
    private JColorChooser chooser;
    private Color currentBackground;

    public ButtonBackgroundChange(JButton button1, Component component, Color currentBackground){
        this.currentBackground = currentBackground;
        chooser = new JColorChooser();
        dialog = JColorChooser.createDialog(component, "Background Color", false /* not modal */, chooser, event -> button1.setBackground(chooser.getColor()), null /* no Cancel button listener */);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        chooser.setColor(currentBackground);
        dialog.setVisible(true);
    }
}

标签: javaswingawt

解决方案


如果您将按钮存储在传递给函数的列表中,您将能够遍历它并为每个按钮设置背景颜色。


推荐阅读