Search code examples
javaswingjtextarea

Writing a line in a JTextArea from another class


I'm trying to use a Method in my class 'Visual' to write a line of code into a JTextArea and it prints when I call it from 'Visual' but when I call it from 'Login' It only prints Text into the Console, not to the TextArea.

private static Visual Visual;
Visual.WriteLine("I'm sorry, your username or password is incorrect. Please try again.");

or

private static Visual Visual = new Visual();
Visual.WriteLine("I'm sorry, your username or password is incorrect. Please try again.");

Dont work form 'Login'

But,

WriteLine("Test"); 

works from 'Visual', the class that the method is in.

Here's the method in 'Visual'

public void WriteLine(String Text) {
    System.out.println(Text);
    SystemFeed.append(Text.toString() + "\n");
    SystemFeed.setCaretPosition(SystemFeed.getDocument().getLength());
}

Solution

  • I can only guess based on the information so far presented (meaning please give us more pertinent information about your problem!) but I fear that you may be having a reference problem, that the GUI reference that you're trying to write to is not the same as the one displayed. Suggestions:

    • Get rid of all unnecessary static variables, including the Visual variable. Make them instance variables.
    • If you get an errors by doing this, the solution is not to make Visual static but to get a reference to a proper instance of this class.
    • Check how many times your program calls new Visual(...) in it. It should only make this call once. Consider putting a System.out.println("New Visual created") in the Visual constructor to see that this is so.
    • Pass a valid reference to the visualized GUI to any objects that need to call methods on this object. So if your Login object needs to call a method of the Visual object, give Login a public void setVisual(Visual visual) method that would allow it to accept the correct Visual reference, make sure that this method is called once during set up of the Login class, and then make sure that in Login you make your Visual method calls with this reference.

    Again if this doesn't help, then tell and show us more, preferably an sscce.