[英]Use ComboBox to change the background color of panel
我正在尝试使用3 ComboBox更改面板的背景颜色,红色,绿色和蓝色可在0-255之间调整。 确实显示了框架和ComboBox,但是当我更改不同的颜色值时,动作监听器不起作用。 我不知道是什么问题。 请帮忙。 谢谢!
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,
greenBox ,
blueBox时, the
侦听器is
null。
public ComboPanel()
{
colorComboBox();
listener = new ChoiceListener();
}
相反,请先初始化listener
...
public ComboPanel()
{
listener = new ChoiceListener();
colorComboBox();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.