Ciphor
Ciphor

Reputation: 742

JTextArea always null?

This is my code, which is pretty simple, it is just creating a JFrame with a JTextArea in the centre.

if(!txtSource.getText().trim().equals("") && txtSource != null)

is never satisfied even when I have entered text into the JTextArea.

I only want to execute methodA() if the JTextArea has some text.

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.");
         }
    }
}

Please help me here...

Upvotes: 3

Views: 719

Answers (2)

SomeShinyObject
SomeShinyObject

Reputation: 7821

It's probably because you never initialize txtSource. Sure you declare it, but just because getTextArea()'s return value is calledtxtSource doesn't assign the class variable as such.

In the test() method you should assign this.txtSource as getTextArea() and then add that to the container.

Upvotes: 2

Reimeus
Reimeus

Reputation: 159854

You're shadowing the txtSource variable, replace

JTextArea txtSource = new JTextArea(20, 80);

with

txtSource = new JTextArea(20, 80);

Upvotes: 7

Related Questions