Domanda

I'm trying to use 3 ComboBox to change the background color of panel, with red, green, and blue adjustable from 0-255. The frame and the ComboBox do show up, however the actionlistener does not work when I change different color values. I have no idea what the problem is. Please help. Thank you!

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();
    }
}
È stato utile?

Soluzione

When you call redBox,greenBox,blueBox, thelistenerisnull`

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

Instead, initialize the listener first...

public ComboPanel()
{
    listener = new ChoiceListener();
    colorComboBox();
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top