有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JRadioButton输入没有响应

我对Java和编程都是新手。我正在尝试一个练习,在这个练习中,我创建了单选按钮,当被选中时可以改变背景颜色。目前我正在使用EclipseIDE

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



    }

共 (2) 个答案

  1. # 1 楼答案

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

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

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

  2. # 2 楼答案

    假设你的意思是

    public class Gui extends JFrame {
    

    不是JRadioButton没有响应,问题是setBackGround直接在帧上被调用,而不是它的可见组件,即ContentPane。你可以使用:

    getContentPane().setBackground(Color.RED);