0

How can I print to a GUI TextArea from outside the Controller class?

I have the method from another class called Alarm:

public boolean maggotAttack(int nothealthy) {
    int maggot = (int) (Math.random() * 2);
    if (maggot == 1) {

        System.out.println("A maggot is destroying the plant, heal the plant!");
        return true;

    } else if (maggot == 0) {
        return false;
    }
    return false;
}

I want the print to get printet to the GUI instead of the console. I do not want to make an instance of my Controller and then use the TextArea in the method above, because that is against good software layers as far as I know.

3 Answers3

0

I think you should study the MVC pattern in detail. If you use this practice, as I suggest you should, then you would have a controller class that holds a reference to a view of some kind. You can then pass that view into your code somehow (e.g. a setter, as a parameter, etc) then use that view to display what you need.

D.B.
  • 4,523
  • 2
  • 19
  • 39
0
JTextAreaOutputStream out = new JTextAreaOutputStream (textArea);
System.setOut (new PrintStream (out));

Use your TextArea to create an JTextAreaOutputStream and redirect the printstream. Then you can always use System.out.println();

0

I got the problem solved by another one in another question i made with more detail. The problem was, that I just needed to set the class which I want to access my controller, as a controller. So the answer is, refer your class as a controller, better shown here: JavaFXML reference to Controller from all classes