2013-06-20 22 views
0

我正在Java中製作一個簡單的計算器,我對Java很新,但是我已經使用它這樣的語言做了很多工作。JCombo Box不更新選定的項目/ Innerclass訪問

問題是,我需要組合框選擇一個項目並使其保持最新狀態,無論是在佔位符還是在框中。

這是設置框架和一切的基本類。

private void initComponents() 
{ 
//TODO:make controls here 
//TODO:DONE 
JFrame calculator = new JFrame("Steven Seppälä"); 
calculator.setLayout(new GridLayout(2, 2, 0, 0)); 
calculator.setSize(400,300); 
//"calculator" is the holder for which all the 
//items must attach to 
calculator.add(new JLabel("Enter the first fraction('1/2')")); 
// calculator.add(new JToolBar.Separator(new Dimension(0,10))); 
calculator.add(field1); 
// calculator.add(new JToolBar.Separator(new Dimension(0,10)));  
//TODO: ADD COMBO BOX HERE 
String[] operationList = {"+","-","*","/"}; 
JComboBox operationBox = new JComboBox(operationList); 


calculator.add(operationBox); 
/*Tried doing the following as well, but it just gave the index 0 consistantly 
    without changeing, regaurdless of if it did change or not     */ 

// String thing = operationBox.getSelectedItem().toString(); 
// System.out.println("Selected Operation is: " + thing); 
// operationCall = operationBox.getSelectedItem(); 

operationBox.addActionListener(new ActionListener() 
{ 
    public void actionPerformed(ActionEvent e) 
    { 
    //DEBUGGING 
    operationBox.getSelectedItem().toString(); 
    } 
}); 

calculator.add(new JLabel("Enter the next fraction('3/4')\n",1)); 
// calculator.add(new JToolBar.Separator(new Dimension(0,0)));  
calculator.add(field2); 
// calculator.add(new JToolBar.Separator(new Dimension(0,0)));  
JButton Cal = new JButton("Calculate"); 
calculator.add(Cal); 

Cal.addActionListener(new ActionListener() 
{ 
    public void actionPerformed(ActionEvent e) 
    { 
    //DEBUGGING 
    System.out.println("Finalizing Calculations..."); 
    calculations(); 
    } 
}); 
//sets exit conditions and the visibility of the window 
calculator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
calculator.setVisible(true); 
calculator.add(new JLabel(results)); 
//TODO: add to(?) frame 
//TODO:DONE 
} 

的計算按鈕動作監聽器工作正常,但是當我編譯,因爲它是現在,我得到錯誤信息:

FractionFrame.java:53: error: local variable operationBox is accessed from within inner class; needs to be declared final 
    System.out.println(operationBox.getSelectedItem().toString()); 
        ^
+0

你有沒有試過可能宣佈它最終? –

+0

我在哪裏以及我將如何宣佈它最終?組合框?動作偵聽器? –

+0

不要讓它最終。使用事件的源對象。 – camickr

回答

3

在ActionListener的,你可以通過訪問該組合框:

JComboBox comboBox = (JComboBox)e.getSource(); 
+0

對不起,我不太明白如何將此代碼實現到我的代碼中... –

+2

您將該行代碼添加到ActionListener。然後你可以在comboBox變量上調用'getSelectedItem()'方法。 – camickr

0

代替:
的JComboBox operationBox =新的JComboBox(operationList);

使其成爲:
final JComboBox operationBox = new JComboBox(operationList);

+1

沒有必要做最後的決定。學習使用事件的源對象。這就是你如何開始編寫可重用的代碼。所有事件偵聽器將包含生成事件的對象。 – camickr

+0

是的,你的答案是最好的答案。我只是給他另一個選擇,以便他可以學習如何閱讀和分析異常。我回答這是因爲根據例外情況,它聲明局部變量operationBox需要聲明爲final。 –