I have two JFrame (JFrame1 and JFrame2) with two JTextField1 and JTextField2. My question is when I write "Hello world " on JTextField2 from Jframe2 and then click on OK button, I see "Hello world " on JTextField1 on Jframe1 class.
How can I do this? I'm sorry if this is a newbie question but I'm learning..
Here is my code:
JFrame2:
private JFrame1 jf1;
private void btn2ActionPerformed(java.awt.event.ActionEvent evt) {
jf1.setjTextField1(this.jTextField2);
}
You could use an Observer Pattern or Producer/Consumer Pattern to solve the problem.
The basic idea is, you have something that generates a value and something that either wants to be notified or consume the generated value.
One of the other prinicples you should take the time to learn is also Code to interface (not implementation). This sounds stranger then it is, but the the idea is to reduce the unnecessary exposure of your objects (to unintended/controlled modifications) and decouple your code, so you can change the underlying implementation without affecting any other code which relies on it
Given the nature of your problem, an observer pattern might be more suitable. Most of Swing's listener's are based on the same principle.
We start by defining the contract that the "generator" will use to provide notification of changes...
Pretty simple. This means we can safely provide an instance of any object that implements this
interface
to the generator and know that it won't do anything to our object, because the only thing it knows about is thetextGenerated
method.Next, we need something that generates the output we are waiting for...
This is just a simple
JPanel
, but it requires you to pass a instance ofTextGeneratorObserver
to it. When the button (or field) triggers theActionListener
, theActionListener
calls thetextGenerated
to notify the observer that the text has been generated or changedNow, we need someone to observer it...
This is a simple
JPanel
which implements theTextGeneratorObserver
interface
and updates it'sJLabel
with the new textThen, we just need to plumb it together