JTextArea始终为null?

3
这是我的代码,非常简单,只是创建了一个带有JTextArea的JFrame。
即使我已经在JTextArea中输入了文本,也无法满足“if(!txtSource.getText().trim().equals("") && txtSource != null)”条件。
我只想在JTextArea中有一些文本时才执行methodA()。
private Container content;
private JTextArea txtSource;

public Test() {
    this.setTitle("Test");
    this.setSize(600,200);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLayout(new BorderLayout());
    content = this.getContentPane();
    content.add(getTextArea(), BorderLayout.CENTER);
    content.add(button(), BorderLayout.SOUTH);
    this.setVisible(true); 
}

private JTextArea getTextArea() {
    JTextArea txtSource = new JTextArea(20, 80);
    return txtSource;
}

private JButton button() {

    JButton btn = new JButton("Click me");

    btn.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
             if(!txtSource.getText().trim().equals("") && txtSource != null) {
                 methodA();
             } else { 
                 System.out.println("Please paste your script in.");
         }
    }
}

请在这里帮忙...

(该句话已翻译)

1
最好将 txtSource != null 放在左边。 - Maroun
当我输入一些文本时,它仍然只执行 System.out.println("Please paste your script in."); - Ciphor
2个回答

7
你正在跟踪变量txtSource,请替换。关于此概念的更多信息,请参见shadowing
JTextArea txtSource = new JTextArea(20, 80);

使用
txtSource = new JTextArea(20, 80);

他所说的“遮蔽”是指在构造函数或方法内重新声明txtSource变量,然后初始化重新声明的变量,从而初始化范围仅限于该方法或构造函数并且将类字段保持为空。正如他展示的解决方案一样,不要在方法或构造函数内重新声明变量。可以在那里初始化变量,但要在类字段上进行,而不是在局部变量上进行。 - Hovercraft Full Of Eels
1
添加了链接以解释变量屏蔽。 - Aubin
1
@HovercraftFullOfEels或者简单地说“隐藏一个字段” - joey rohan

2

可能是因为您从未初始化txtSource。确实,您已经声明了它,但只是因为getTextArea()的返回值被称为txtSource并不会将类变量分配为这样。

test()方法中,您应该将this.txtSource分配为getTextArea(),然后将其添加到容器中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接