JButton isselected方法不起作用 [英] JButton isselected method doesnt work

查看:106
本文介绍了JButton isselected方法不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码用于在选择三个按钮中的任何一个时更改背景的颜色:红色,绿色或蓝色.当我选择其中任何一个时,实际上什么也没有发生.但是,从JButton更改为JRadioButtons或JToggleButtons确实可以.有人知道为什么吗?是因为JButton.isselected()方法被错误检查并且始终返回false吗?感谢您的帮助...谢谢.

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

推荐答案

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

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

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

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

这篇关于JButton isselected方法不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆