java - JRadiobutton ActionListener 没有响应

标签 java swing user-interface

我正在注册两个 JRadiobutton 的事件,但没有任何反应!没有抛出任何错误,所以我无法追溯到问题所在。 选择第一个单选按钮时,它应该打印出一条文本。当选择第二个按钮时,它应该打印出不同的文本......

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;


public class num2 extends JFrame  {
    private static JLabel type;
    private static JLabel days;
    private static JLabel amt;
    private static JRadioButton checkStandard;
    private static JRadioButton checkExecutive;
    private static JTextField txtDays;
    private static JTextField txtAmount;
    private static JButton btnCalculate;
    private static ButtonGroup group = new ButtonGroup();

    public num2(){
        super("Testing Events");
        JPanel p = new JPanel();
        JLabel type = new JLabel("Room Type : ");
        JLabel days = new JLabel("Number Of Days : ");
        JLabel amt = new JLabel("Total Amount : ");

        JRadioButton checkStandard = new JRadioButton("Standard");
        JRadioButton checkExecutive = new JRadioButton("Executive");




        p.setLayout(new FlowLayout());


        group.add(checkStandard);
        group.add(checkExecutive);
        p.add(checkStandard);
        p.add(checkExecutive);
        TheHandler handler = new TheHandler();
        checkStandard.addActionListener(handler);
        checkExecutive.addActionListener(handler);
        add(p);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(100, 100);
        setVisible(true);

    }

    public static void main(String[] args) {
        num2 app = new num2();


    }


private class TheHandler implements ActionListener{
    public void actionPerformed(ActionEvent evt) {
        Object source = evt.getSource();
        if (source == checkStandard) {
            System.out.println("Done");
         }
        else if(source == checkExecutive){
            System.out.println("nope");
        }

}
}



}

最佳答案

你是shadowing两个 JRadioButton 变量

JRadioButton checkStandard = new JRadioButton("Standard");
JRadioButton checkExecutive = new JRadioButton("Executive");

应该是

checkStandard = new JRadioButton("Standard");
checkExecutive = new JRadioButton("Executive");

关于java - JRadiobutton ActionListener 没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22901520/

相关文章:

java - XML 文档的索引路径

java - 如何配置/减少 tcp 段大小

java - 如何在 JTextArea 中打印循环的结果?

python - 是否有用于自定义自动完成的 Python 库?

java - IntelliJ Idea GUI 表单 : Null Layout

java - 使用 Swing 按钮重置应用程序

java - 如何确定 eclipse 用于启动我的 java 程序的命令字符串?

java - Java 中的类转换异常

java - 为 JButton 定义背景颜色和前景图标?

java - 使两个物体同时旋转