2014-04-06 68 views
0

我正在註冊兩個JRadiobuttons的事件,但沒有任何反應!沒有錯誤拋出,所以我不能追溯到這個問題。 當選擇第一個單選按鈕時,它應該打印出一個文本。當選擇第二個按鈕,它應該打印出不同的文本....JRadiobutton ActionListener沒有響應

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

} 
} 



} 

回答

5

shadowingJRadioButton變量

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

應該

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

+1打字更快,但我也忙於輸入,你不應該使用靜態變量,因爲這不是必需的。 – camickr

+0

正要補充說明...... :) – Reimeus