JButton isselected method doesnt work

廉价感情. 提交于 2019-12-13 14:24:51

问题


The code below is to change the colour of the background on selecting any of the 3 buttons: red, green or blue. When I select either of them, nothing actually happens. However, changing from JButtons to JRadioButtons or JToggleButtons does work. Anyone knows why? Is it because JButton.isselected() method is bugged and it always returns false? I appreciate any help...thank you.

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:


The isSelected() method would work for toggle buttons, not for regular buttons.

In your case you have to to track the source of the event. You can get the clicked button with event.getSource().



来源:https://stackoverflow.com/questions/12337659/jbutton-isselected-method-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!