FirmView
FirmView

Reputation: 3150

Updating jtextarea from another class

I have two classes,

  1. Main

  2. Sub

In main class, i have a button and jtextarea

In Sub class, i hava a button

when i click on the button in main class, the Sub class runs and shows a button. When i press on the button in the Sub class, the jtextarea should show the value, "Sample text", but jtextarea is not showing any text.

Sub class code,

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    Main main = new Main();
    main.jTextArea1.setText("Sample text");
}

Upvotes: 0

Views: 2616

Answers (2)

Tobb
Tobb

Reputation: 12180

You shouldn't new Main, then you get a different object (that is probably not set to be visible), and nothing will be shown. What you need to do is create a local variable for your Main-object (the one that is showing), as well as a constructor in Sub, like this:

private Main main;
public Sub(final Main main) {
    this.main = main();
}

then, when you instantiate Sub from Main:

final Sub sub = new Sub(this);

Then your action in Sub can just say:

main.jTextArea1.setText("Sample text")

or even better:

main.getjTextArea1().setText("Sample text");

You should always keep your variables private, and use methods to manipulate them, getters and setters, or something else. You could for instance do it like this:

main.displayText("Sample text");

This way, Sub does not need to know anything about Mains text area, which is a good thing.

Upvotes: 4

Angelos Chalaris
Angelos Chalaris

Reputation: 6747

As far as the main reference is to an object and not the class itself it SHOULD work! However you shall check if the jTextArea1 is public or private. If private make a getTextArea() method return the textarea and call the method (generally that is a better idea). If sub class is called from the main class and main is a parent try to getting the rootPane (e.g. sub is a JDialog). Try making a main window externally (in another class) to see how it goes. This solved my problem once in calls between different frames and Dialogs!

Upvotes: 0

Related Questions