我正在尝试将ActionListener添加到我的Java程序中的一个按钮,但是它的方法会导致错误发生。这是我的代码:
import javax.swing.*;//import the packages needed for gui
import java.awt.*;
import java.awt.event.*;
public class Calculator {
public static void main(String[] args) {
JFrame window = new JFrame("Window");// makes a JFrame
window.setSize(300, 350);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new FlowLayout());// makes the panel,
// textfield and buttons
JTextField textField = new JTextField(20);
JButton openbracket = new JButton("(");
JButton closebracket = new JButton(")");
JButton clearbutton = new JButton("C");
JButton arcsin = new JButton("arcsin");
JButton arccos = new JButton("arccos");
JButton arctan = new JButton("arctan");
JButton sin = new JButton("sin");
JButton cos = new JButton("cos");
JButton tan = new JButton("tan");
JButton log = new JButton("log");
JButton seven = new JButton("7");
JButton eight = new JButton("8");
JButton nine = new JButton("9");
JButton four = new JButton("4");
JButton five = new JButton("5");
JButton six = new JButton("6");
JButton one = new JButton("1");
JButton two = new JButton("2");
JButton three = new JButton("3");
JButton zero = new JButton("0");
JButton radixpoint = new JButton(".");
JButton equal = new JButton("=");
String values = null;
class Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
values = values + "3";
textField.setText(values);
}
}
panel.add(textField);// adding all the things
window.add(panel);
panel.add(openbracket);
panel.add(closebracket);
panel.add(clearbutton);
panel.add(arcsin);
panel.add(arccos);
panel.add(arctan);
panel.add(sin);
panel.add(cos);
panel.add(tan);
panel.add(log);
panel.add(nine);
panel.add(eight);
panel.add(seven);
panel.add(six);
panel.add(five);
panel.add(four);
panel.add(three);
panel.add(two);
panel.add(one);
panel.add(zero);
panel.add(radixpoint);
panel.add(equal);
window.setVisible(true);
}
}
我收到的错误消息是:
Calculator.java:36: local variable values is accessed from within inner class; needs to be declared final values = values + "3"; ^
Calculator.java:36: local variable values is accessed from within inner class; needs to be declared final values = values + "3"; ^
Calculator.java:37: local variable values is accessed from within inner class; needs to be declared final textField.setText(values); ^
Calculator.java:37: local variable textField is accessed from within inner class; needs to be declared final textField.setText(values); ^
4 errors
编译器希望我将String对象和JTextField对象声明为final,但如果我将它们声明为final,我将无法更改它们。如何在不更改对象的情况下使计算器正常工作?
答案 0 :(得分:1)
好吧,为了使这段代码能够编译,你需要将String
值和JTextField textField
作为main的静态成员。这是因为那些来自静态主方法。
public class Calculator {
static String values = null;
static JTextField textField = new JTextField(20);
...