在尝试从JTextField
读取数据时,它说:
cannot refer to non final variable declared in inner class in another method
CODE:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Soloswing {
Soloswing() {
JFrame jf = new JFrame("soloworld");
jf.setLayout(new FlowLayout(5, 25, 10));
JLabel l1 = new JLabel("VALUE1");
JTextField t1 = new JTextField(20);
JLabel l2 = new JLabel("VALUE2");
JTextField t2 = new JTextField(20);
JLabel l3 = new JLabel("RESULT");
JTextField t3 = new JTextField(20);
JButton b1 = new JButton("+");
JButton b2 = new JButton("-");
JButton b3 = new JButton("*");
JButton b4 = new JButton("/");
JButton b5 = new JButton("%");
JButton bequals = new JButton("=");
JButton bclear = new JButton("CE");
//int i = Integer.parseInt(t1.getText());
//int j = Integer.parseInt(t2.getText());
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(300, 500);
jf.add(l1);
jf.add(t1);
jf.add(l2);
jf.add(t2);
jf.add(l3);
jf.add(t3);
jf.add(b1);
jf.add(b2);
jf.add(b3);
jf.add(b4);
jf.add(b5);
jf.add(bequals);
jf.add(bclear);
jf.setVisible(true);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int j = Integer.parseInt(t2.getText());
int k = i + j;
t3.setText(k);
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Soloswing();
}
});
}
}
所以,我期望的是,当点击JButton
时,它应该读取两个JTextField
的输入并将它们添加到一起并在第三个textField中显示结果
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int j = Integer.parseInt(t2.getText());
int k = i + j;
t3.setText(k);
}
});
但是,它显示错误:
canot refer to non final variable declared in inner class in another method