I have two classes,
-
Main
-
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");
}
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:
then, when you instantiate Sub from Main:
Then your action in Sub can just say:
or even better:
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:
This way, Sub does not need to know anything about Mains text area, which is a good thing.