How can I access the same text area variable?

Tags: , ,



The code below works as such:

  • User clicks the run button
  • Program reads the file from designated location
  • Program removes content from <script> </script>, including tags themselves
  • Program returns edited text into JTextArea called textArea

I’ve tried making it a global variable since it’s in two different classes. The run down is that once the user clicks the “run button”, the text area initialised in the GUI class will update.

public class GUI{
        static JTextArea textArea;
    public GUI() {
        JFrame frame = new JFrame();
        textArea = new JTextArea(5,30);
        JButton runButton = new JButton("Remove JS");
        JButton importButton = new JButton("Import File");
        JPanel panel = new JPanel();
        
        runButton.addActionListener(new runApp());
        runButton.setBounds(100, 100, 100, 80);
        importButton.addActionListener(new importFile());
        importButton.setBounds(100, 100, 80, 60);
        
        panel.setBorder(BorderFactory.createEmptyBorder(300, 300 , 150, 150));
        panel.setLayout(new GridLayout(0, 1));
        panel.add(textArea);
        panel.add(runButton);
        panel.add(importButton);
        
        frame.add(panel, BorderLayout.CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("JavaScript Extractor");
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new GUI();

    }
}

class runApp implements ActionListener{
    public void actionPerformed(ActionEvent arg0) {
        
        RemoveScript run = new RemoveScript();
        

        try {
            File fileObject = new File("C:\Users\coker\Documents\readJS.txt");
            Scanner reader = new Scanner(fileObject);
            while(reader.hasNextLine()) {
                String output = reader.nextLine();
                textArea.setText(run.removeScript(output));
            }
            reader.close();
        }catch(FileNotFoundException e) {
            System.out.println("An error has occured.");
            e.printStackTrace();
        }
    }
}

Answer

3 options:

  • Make your listener class an inner class of GUI, then it will have access to all fields of it’s outer class (no need for static in that case)
  • Keep the 2 classes completely separate, and pass a reference to the text field to the listener (e.g. via constructor parameter).
  • access the static field via GUI.textArea


Source: stackoverflow