3

下面的代码是在选择 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));
        }
}
}
4

1 回答 1

7

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

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

于 2012-09-09T08:42:14.687 回答