我正在用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());
^
答案 0 :(得分:3)
在ActionListener中,您可以使用以下命令访问组合框:
JComboBox comboBox = (JComboBox)e.getSource();
答案 1 :(得分:0)
而不是:
JComboBox operationBox = new JComboBox(operationList);
成功:
final JComboBox operationBox = new JComboBox(operationList);