JTextArea always null?

java, jbutton, jframe, jtextarea, swing

Solution

You're shadowing the `txtSource` variable, replace

JTextArea txtSource = new JTextArea(20, 80);

with

txtSource = new JTextArea(20, 80);

Problem

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...

Original source