3

这是我的代码,非常简单,它只是在中心创建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.");
         }
    }
}

请在这里帮我...

4

2 回答 2

7

你正在隐藏txtSource变量,替换

JTextArea txtSource = new JTextArea(20, 80);

txtSource = new JTextArea(20, 80);
于 2013-03-31T14:57:18.923 回答
2

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

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

于 2013-03-31T14:57:51.203 回答