How do I Update JTextField text from another panel object

I have 4 panels running on one frame .. each panel has its own class where. each panel class has its own widgets and layout. I’m trying to update panel2’s textField from panel1’s textField input.

I have tried calling panel2.textfield.setText(“what ever text needed”); on panel1’s textfield actionEvent the value does changes when I check on system.out.println() method but the swing UI doesn’t change unless the two textfields are defined under one constructor which is something I don’t want

this is just a concept to have you understand what i wanna do.

class1 extends JPanel{
JTextField textfield1;
class1(){
 textfield1 = JTextField();
 add(textfield1);
 textfield1.addActionListener((ActionEvent evt)->{
  change(evt);
  system.out.println(textfield1.getText())
});
}
void change(ActionEvent evt){
  new Class2.textfield2.setText("y");
}
}

class2 extends JPanel{
JTextfield textfield2;
class2(){
 texfield2 = new JTextField("x");
 add(textfield2);
}
}

Mainclass extends JFrame{
Mainclass(){
setOnDef....(JFrame.exit_onclose);
 Class1 class1 = new Class1();
 Class2 class2 = new Class2();

add(class1);
add(class2);
pack();
}

public void main(String[]args){
SwingUtilities.invokelater(()->{
 new Mainclass.setVisible(true);
});
}
}

I expect X to change to Y .I have tried everything swingWorker, invokelater, creating a string variable that will hold the text to pass via constructor, nothing but putting everything in one class works seems to work

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

Your problem lies in this line:

new Class2.textfield2.setText("y");

By calling new Class2() you create a new instance of Class2 and afterwards change something in it. The instance of Class2 in your frame stays the same. To solve this you have to get a reference to the object in your frame, for example by passing it over in the constructor, like this:

In Class1

Class2 class2;

Class1(Class2 class2) {
  this.class2 = class2;
  // Other constructor stuff
}

void change(...) {
  class2.textfield2.setText("y);
}

And in Mainclass‘ constructor

Class2 class2 = new Class2();
Class1 class1 = new Class1(class2);

This way change really changes the TextField that is displayed.