java:Cannot refer to a non-final variable tx inside an inner class defined in a different methodpublic class ActionIf extends JFrame {\x09private static final long serialVersionUID = 1L;\x09User u=null;\x09JTextField tx=null;\x09JButton jb=null;\x09p

来源:学生作业帮助网 编辑:六六作业网 时间:2024/12/27 01:12:49
java:Cannotrefertoanon-finalvariabletxinsideaninnerclassdefinedinadifferentmethodpublicclassActionIf

java:Cannot refer to a non-final variable tx inside an inner class defined in a different methodpublic class ActionIf extends JFrame {\x09private static final long serialVersionUID = 1L;\x09User u=null;\x09JTextField tx=null;\x09JButton jb=null;\x09p
java:Cannot refer to a non-final variable tx inside an inner class defined in a different method
public class ActionIf extends JFrame {
\x09private static final long serialVersionUID = 1L;
\x09User u=null;
\x09JTextField tx=null;
\x09JButton jb=null;
\x09private void showtext(){
\x09\x09
\x09\x09JTextField tx=new JTextField();
\x09\x09User u=new User();
\x09\x09JButton jb=new JButton();
\x09\x09this.setSize(300,300);
\x09\x09this.setLayout(null);
\x09\x09tx.setSize(50,50);
\x09\x09tx.setBounds(50,50,50,50);
add(tx);
jb.setBounds(100,100,50,50);
jb.addActionListener(new java.awt.event.ActionListener(){
\x09\x09\x09public void actionPerformed(java.awt.event.ActionEvent e) {
\x09\x09\x09\x09String str=tx.getText();
\x09\x09\x09\x09
\x09\x09\x09\x09
\x09\x09\x09\x09
\x09\x09\x09}
\x09
\x09
\x09
});
tx不能写在那里吗?

java:Cannot refer to a non-final variable tx inside an inner class defined in a different methodpublic class ActionIf extends JFrame {\x09private static final long serialVersionUID = 1L;\x09User u=null;\x09JTextField tx=null;\x09JButton jb=null;\x09p
final JTextField tx = null;
// 使用匿名内部类,隐式调用外部变量,外部变量需要final修饰.
jb.addActionListener(new java.awt.event.ActionListener(){
    public void actionPerformed(java.awt.event.ActionEvent e) {
\x09String str = tx.getText();
}