2011-12-12 41 views
0

每次我點擊我的代碼上的提交按鈕時,它會給我每小時的字符串值?即使我的JComboBox中的項目具有每週的當前值?我該如何解決這個問題?JComboBox當前值使用

我ComputeWindow

public class ComputeWindow extends JFrame{ 

     private JLabel payRate,employeeID,payType,gWage; 
     private JTextField empRate,idTxt,gWageTxt; 
     private JComboBox rateChooser; 
     private JPanel panel; 
     private JButton generate; 

     public ComputeWindow(){ 

      super("Gross Wage"); 
      setSize(300, 150); 
      setLocationRelativeTo(null); 
      setVisible(true); 
      setDefaultCloseOperation(EXIT_ON_CLOSE); 


      String[] employeeType = {"Hourly","Bi Weekly","Weekly","Base"}; 

      employeeID = new JLabel("Employee ID: "); 
      payRate = new JLabel("Employee Rate: "); 
      payType = new JLabel("Pay Type: "); 
      gWage = new JLabel("Gross Wage"); 
      empRate = new JTextField(10); 
      idTxt = new JTextField(10); 
      gWageTxt = new JTextField(10); 
      generate = new JButton("Compute!"); 
      rateChooser = new JComboBox(employeeType); 
      panel = new JPanel(new GridLayout(5,1)); 

      panel.add(employeeID); 
      panel.add(idTxt); 
      panel.add(payRate); 
      panel.add(empRate); 
      panel.add(payType); 
      panel.add(rateChooser); 
      panel.add(gWage); 
      panel.add(gWageTxt); 
      panel.add(generate); 
      add(panel, BorderLayout.CENTER); 
      String Option =(String)rateChooser.getSelectedItem(); 

      GenerateHandler generateHandler = new GenerateHandler(); 
      generate.addActionListener(generateHandler); 
      generateHandler.setOption(Option); 
     } 
    } 

和處理程序這裏是

private class GenerateHandler implements ActionListener{ 

     String option; 

     public void setOption(String option){ 
      this.option = option; 
     } 

     public void actionPerformed(ActionEvent e) { 

      if(option =="Hourly"){ 
       JOptionPane.showMessageDialog(null,option); 
      }else if(option == "Weekly"){ 
       JOptionPane.showMessageDialog(null,option); 
      } 
     } 

    } 

} 

任何建議的代碼?關於如何解決這個問題?或者它會返回或顯示我在JComboBox中使用的當前值?

+0

請學習java的命名約定並堅持他們 – kleopatra

回答

2

你可以改變你的代碼如下:

GenerateHandler generateHandler = new GenerateHandler(rateChooser); 

private class GenerateHandler implements ActionListener{ 
    JComboBox rateChooser; 

    public GenerateHandler(JComboBox rateChooser){ 
     this.rateChooser = rateChooser; 
    } 

    public void actionPerformed(ActionEvent e) { 
     String Option =(String)rateChooser.getSelectedItem(); 
     if("Hourly".equals(option)){ 
      JOptionPane.showMessageDialog(null,option); 
     }else if("Weekly".equals(option)){ 
      JOptionPane.showMessageDialog(null,option); 
     } 
    } 
} 

上面的代碼將解決您的解決方案,但是這不是一個好的做法,延長JFrame的,特別是JSomething ...並按照完成的方式初始化構造函數中的所有內容。

+0

那我該怎麼做呢?或者什麼是正確的方法呢? – user962206

+0

在會議中:(現在,它應該需要一些時間來exmplain。但作爲一個開始,這是探索 – Kowser

+0

okey沒關係,我會等待,我沒有太多的想法與GUI的我剛剛開始 – user962206