JButton选择的方法不起作用

时间:2012-09-09 08:38:01

标签: java swing selection jbutton jtogglebutton

以下代码用于在选择3个按钮中的任何一个时更改背景颜色:红色,绿色或蓝色。当我选择其中任何一个时,实际上什么也没发生。但是,从JButtons更改为JRadioButtons或JToggleButtons确实有效。谁知道为什么?是因为JButton.isselected()方法被窃听并且它总是返回false?我感谢任何帮助......谢谢。

public class bgcolor2 extends JFrame
{
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT= 400;
private ActionListener listener;
private JButton greenbutton;
private JButton redbutton;
private JButton bluebutton;
private JPanel colorpanel;
private JPanel buttonpanel;

public bgcolor2()
{
    colorpanel = new JPanel();
    add(colorpanel,BorderLayout.CENTER);

    class bgcolorlistener implements ActionListener
    {
        public void actionPerformed(ActionEvent event)
        {
            changebgcolor();    
        }
    }
    listener=new bgcolorlistener();
    createbuttons();
    setSize(FRAME_WIDTH,FRAME_HEIGHT);
}

public void createbuttons()
{
    greenbutton = new JButton("Green");
    greenbutton.addActionListener(listener);
    bluebutton = new JButton("Blue");
    bluebutton.addActionListener(listener);
    redbutton = new JButton("Red");
    redbutton.addActionListener(listener);
    buttonpanel = new JPanel();

    buttonpanel.add(greenbutton);
    buttonpanel.add(redbutton);
    buttonpanel.add(bluebutton);
    add(buttonpanel,BorderLayout.SOUTH);
}

public void changebgcolor()
{
    if (greenbutton.isSelected()) 
        {
            colorpanel.setBackground(new Color(0,255,0));
        }
    if (bluebutton.isSelected()) 
        {
            colorpanel.setBackground(new Color(0,0,255));
        }
    if (redbutton.isSelected()) 
        {
            colorpanel.setBackground(new Color(255,0,0));
        }
}
}

1 个答案:

答案 0 :(得分:7)

isSelected()方法适用于切换按钮,而不适用于常规按钮。

在您的情况下,您必须跟踪事件的来源。您可以使用event.getSource()获得点击的按钮。