【问题标题】:JTextArea always null?JTextArea 总是为空?
【发布时间】:2013-03-21 18:33:24
【问题描述】:

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

if(!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 != null 最好在左边。
  • 当我输入一些文本时,它仍然只是执行System.out.println("Please paste your script in.");

标签: java swing jframe jbutton jtextarea


【解决方案1】:

这可能是因为您从未初始化txtSource。当然你声明了它,但仅仅因为getTextArea() 的返回值被称为txtSource 并没有像这样分配类变量。

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

【讨论】:

    【解决方案2】:

    你是shadowing txtSource 变量,替换

    JTextArea txtSource = new JTextArea(20, 80);
    

    txtSource = new JTextArea(20, 80);
    

    【讨论】:

    • 他所说的“遮蔽”的意思是,通过在构造函数或方法中重新声明 txtSource 变量,然后初始化重新声明的变量,您正在初始化一个范围仅限于方法或构造函数,并将类字段保留为空。正如他所展示的,解决方案是不要在方法或构造函数中重新声明变量。当然继续并在那里初始化变量,但在类字段上这样做,而不是在局部变量上。 1+
    • 添加了解释阴影的链接
    • @HovercraftFullOfEels 或简单地“隐藏字段”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-27
    • 1970-01-01
    相关资源
    最近更新 更多