简体   繁体   中英

JRadiobutton ActionListener not responding

I'm registering the events for two JRadiobuttons, but nothing happens! No errors are thrown, so I'm not being able to trace back the problem.. When selecting the first radio button, it should print out a text. When selecting the second button, it should print out a different text....

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

}
}



}

You're shadowing both JRadioButton variables

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

should be

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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