繁体   English   中英

JRadioButton输入没有响应

[英]JRadioButton Input not responding

我是Java的新手,也是一般的编程。我正在尝试一种练习,我可以创建单选按钮,在选择时更改背景颜色。我正在使用Eclipse IDE。

Eclipse没有给我任何错误,我可以正常运行b / m程序,无线电按钮显示并可点击。但是,当我选择它们时,单选按钮无法改变背景颜色。 我很感激我能得到的任何答案和指示。

谢谢!

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;


    public class Gui{
    //Declares Variables
    JRadioButton red=new JRadioButton("red");
    JRadioButton blue=new JRadioButton("blue");
    JRadioButton yellow=new JRadioButton("yellow");
    ButtonGroup group = new ButtonGroup();
    //Constructor
    public Gui(){
        //Sets title
        super("RadioButton Exercise");
        //Sets layout as default
        setLayout(new FlowLayout());
        //Adds the JRadioButtons
        add(red);
        add(blue);
        add(yellow);
        //Groups the variables
        group.add(red);
        group.add(blue);
        group.add(yellow);
        //Creates HandlerClass object
        HandlerClass handler = new HandlerClass();
        //When buttons are clicked, HandlerClass is called
        red.addItemListener(handler);
        blue.addItemListener(handler);
        yellow.addItemListener(handler);


    }

    public class HandlerClass implements ItemListener{
        public void itemStateChanged(ItemEvent x){
            if(x.getSource()==red){
                setBackground(Color.RED);
            }
            else if(x.getSource()==blue){
                setBackground(Color.BLUE);
            }
            else{
                setBackground(Color.YELLOW);
            }
        }
    }



    }

假设你的意思

public class Gui extends JFrame {

并不是JRadioButton没有响应,问题是直接在框架上调用setBackGround ,而不是它的可见组件,即ContentPane 您可以使用:

getContentPane().setBackground(Color.RED);

你有像x.getSource()==red这样的条件。 它不比较objects ; 它比较object references 因此,即使两个不同的对象引用指向同一个对象,这样的表达式也会产生False

如果要比较对象,则需要使用equals方法。 equal以产生有意义的结果的两个对象应该是相同类型的。

我建议如下: (JradioButton)x.getSource().equals(red);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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