简体   繁体   中英

JButton isselected method doesnt work

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));
        }
}
}

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM