- Java code
final JTextField jtf = new JTextField(20); JButton jbutton_ok = new JButton("ok!"); JButton jbutton_no = new JButton("no!"); jbutton_ok.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { if(e.getActionCommand().equals("ok!")){ System.out.println(jtf.getText());//不加final这里会报错 } } });
在第一行代码之中,如果我不加上final编译时就会报错,求解为何
------解决方案--------------------------------------------------------
规定。内部类访问局部变量只有其是final的时候才能访问
------解决方案--------------------------------------------------------
你可以在方法外先创建一个JTextField
- Java code
JButton jbutton_ok = new JButton("ok!"); JButton jbutton_no = new JButton("no!"); jbutton_ok.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { if(e.getActionCommand().equals("ok!")){ System.out.println(jtf.getText());//不加final这里会报错 } } });//所有方法外private javax.swing.JTextField jtf = new javax.swing.JTextField(20);