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 回答
0

而不是:
JComboBox operationBox = new JComboBox(operationList);

实现:
最终 JComboBox operationBox = new JComboBox(operationList);

于 2013-06-20T02:28:22.777 回答