Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java JTextArea总是空的吗?_Java_Swing_Jframe_Jbutton_Jtextarea - Fatal编程技术网

Java JTextArea总是空的吗?

Java JTextArea总是空的吗?,java,swing,jframe,jbutton,jtextarea,Java,Swing,Jframe,Jbutton,Jtextarea,这是我的代码,非常简单,它只是创建了一个JFrame,中间有一个JTextArea 如果(!txtSource.getText().trim().equals(“”&&txtSource!=null) 即使我在JTextArea中输入了文本,也不会满足 我只想在JTextArea有一些文本时执行methodA() private Container content; private JTextArea txtSource; public Test() { this.setTitle("

这是我的代码,非常简单,它只是创建了一个
JFrame
,中间有一个
JTextArea

如果(!txtSource.getText().trim().equals(“”&&txtSource!=null)

即使我在JTextArea中输入了文本,也不会满足

我只想在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.");
         }
    }
}
请在这里帮助我…

您是
txtSource
变量,请替换

JTextArea txtSource = new JTextArea(20, 80);


这可能是因为您从未初始化
txtSource
。确实声明了它,但仅仅因为调用了
getTextArea()
的返回值
txtSource
并没有这样分配类变量


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

txtSource!=null
最好在左边。当我输入一些文本时,它仍然只执行
System.out.println(“请将脚本粘贴进来”)他所说的“隐藏”是指,通过在构造函数或方法中重新声明txtSource变量,然后初始化重新声明的变量,您正在初始化一个变量,该变量的作用域仅限于方法或构造函数,并将类字段保留为空。如他所示,解决方案是不在方法或构造函数内部重新声明变量。一定要在那里初始化变量,但是要在class字段上初始化,而不是在局部变量上初始化。添加1+链接以解释shadowing@HovercraftFullOfEels或者干脆“隐藏字段”
txtSource = new JTextArea(20, 80);