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...
You're shadowing the txtSource variable, replace
JTextArea txtSource = new JTextArea(20, 80);
with
txtSource = new JTextArea(20, 80);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With