java - 使用 ComboBox 更改面板的背景颜色

标签 java swing jcombobox

我正在尝试使用3个ComboBox来更改面板的背景颜色,红色、绿色和蓝色可在0-255之间调节。框架和组合框确实显示了,但是当我更改不同的颜色值时, Action 监听器不起作用。我不知道问题是什么。请帮忙。谢谢!

public class ComboPanel extends JPanel {

private JLabel Label1;
private JLabel Label2;
private JLabel Label3;
private JComboBox red;
private JComboBox green;
private JComboBox blue;
private ActionListener listener;

public ComboPanel()
    {
        colorComboBox();
        listener = new ChoiceListener();
    }

    class ChoiceListener implements ActionListener
    {
        public void actionPerformed(ActionEvent event)
        {
            setColor();
        }
    }

    public JComboBox redBox()
    {
        red = new JComboBox();
        int max_red = 255;
        for (int i = 0; i <= max_red; i++)
        {
            red.addItem(i);
        }
        red.setEditable(false);
        red.addActionListener(listener);
        return red;
    }

    public JComboBox greenBox()
    {
        green = new JComboBox();
        int max_green = 255;
        for (int i = 0; i <= max_green; i++)
        {
            green.addItem(i);
        }
        green.setEditable(false);
        green.addActionListener(listener);
        return green;
    }

    public JComboBox blueBox()
    {
        blue = new JComboBox();
        int max_blue = 255;
        for (int i = 0; i <= max_blue; i++)
        {
            blue.addItem(i);
        }
        blue.setEditable(false);
        blue.addActionListener(listener);
        return blue;
    }

    public void colorComboBox()
    {
        setLayout(new GridLayout(3, 1));
        Label1 = new JLabel("Red");
        Label2 = new JLabel("Green");
        Label3 = new JLabel("Blue");

        add(Label1);
        add(redBox());
        add(Label2);
        add(greenBox());
        add(Label3);
        add(blueBox());
    }

    public void setColor()
    {
        int red_number = (int) red.getSelectedItem();
        int green_number = (int) green.getSelectedItem();
        int blue_number = (int) blue.getSelectedItem();
        setBackground(new Color(red_number, green_number, blue_number));
        repaint();
    }
}

最佳答案

当你调用redBox、greenBoxblueBox时,监听器null`

public ComboPanel()
{
    colorComboBox();
    listener = new ChoiceListener();
}

相反,首先初始化监听器...

public ComboPanel()
{
    listener = new ChoiceListener();
    colorComboBox();
}

关于java - 使用 ComboBox 更改面板的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23101811/

相关文章:

java - JComboBox 中的空值停止箭头键使用

java - 如何使用 JRadioButtons 更改组合框

java - 简化在 Java 中使用一个对象还是另一个对象的决定

java - Java错误类枚举问题

java - JToolBar始终 float

java - 如何更改 JFrame 的背景颜色(我是大学一年级学生)

java - Boxlayout 中 JPanel 周围的空白区域?

java - 如何对JTable中JComboBox的字符串进行排序?

java - 编写一次代码并在我想再次运行它时添加引用?

JavaEE : Web Service Deployed Successfully but Tester is not Working