0

I have a class "MainFrame1" that extends a JFrame and also another class that is a file chooser. Whenever I press one of the JMenuItems in MainFrame1 class, I want the file chooser to open up and load up the text of the chosen file on a JTextArea that was created in MainFrame1 class. This works perfectly fine as I created a separate class implementing an ActionListener. Now my problem is that when I press another JMenuItem I want to do something else to the text in the JTextArea. I have implemented another ActionListener for that in a different class but the problem is that the JTextArea seems to be empty when I do that although I can see the text in there. Thanks in advance.

This is how I have created the JTextArea in the MainFrame1:

showAction = new JTextArea(10,10);
showAction.setEditable(false);
showAction.setFont(new Font("Arial", Font.BOLD, 12));
add(showAction, BorderLayout.NORTH);    

And this is my second ActionListener class (also, whenever the text of a file is printed in the JTextArea, the text "loaded up." will also be printed) and I always get the else branch.

public class TransformController implements ActionListener{

    MainFrame1 mf;
    public TransformController(MainFrame1 mf) {
        this.mf = mf;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        String text = mf.showAction.getDocument().toString();
        if(text.contains("loaded up.")) {
            char[] charText = text.toCharArray();
            Parser parser1 = new Parser(charText);
            parser1.packageVisitor();
        }
        else {
            System.out.println("Load up a Java file first!");
        }
    }   
}
Phonolog
  • 6,321
  • 3
  • 36
  • 64
Laura
  • 1
  • 3

1 Answers1

0

This seems to be mostly a debugging question: First, find out what's in showAction.getDocument() to see if your menu item just isn't loading it right. Then check (with an IDE or via toString()) that mf.showAction really is the same object in the two cases.

Structurally, there's nothing in Java that prevents you from having a reference to the same JTextArea in two parts of the code, and reading the text out of it for different purposes.

Bob Jacobsen
  • 1,150
  • 6
  • 9
  • Thanks for the suggestion. Apparently I only had to use .getText() instead of getDocument(). – Laura Feb 18 '18 at 18:29