0

私は Java で簡単な計算機を作成しています。私は Java にはかなり慣れていませんが、そのような言語で多くの作業を行ってきました。

問題は、コンボ ボックスで項目を選択し、プレース ホルダーまたはボックス自体で最新の状態に保つ必要があることです。

これは、フレームとすべてをセットアップする基本クラスです。

  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());
                       ^
4

2 に答える 2

3

ActionListener では、次を使用してコンボ ボックスにアクセスできます。

JComboBox comboBox = (JComboBox)e.getSource();
于 2013-06-20T02:23:34.830 に答える