gpt4 book ai didi

java - JRadioButton 输入无响应

转载 作者:行者123 更新时间:2023-12-02 07:08:24 26 4
gpt4 key购买 nike

我是 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,而不是它的可见组件,即 >内容 Pane 。您可以使用:

getContentPane().setBackground(Color.RED);

关于java - JRadioButton 输入无响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15835334/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com