Question

I have a jFrame1, two JTextField. One of the text fields should load the data from my jFrame2. In my jFrame1 I have a button that opens the jFrame2. When you press the button opens jFrame2, you can see 4 buttons, and when you press one of the buttons, the jframe2 should close and load a string in one of my text fields.

Anyone know how I can do this? Because I have tried several codes and does not leave me.

This is my example code:

public class jFrame1 extends javax.swing.JFrame{

   public JTextField txt1; 
   private JButton btn1;

   btn1.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
         jFrame2 jframe2 = new jFrame2(this);
         jframe2.setVisible(true);
      }
   });


   .....

}


public class jFrame2 extends javax.swing.JFrame{

   private JFrame jframe1;

   public jFrame2(JFrame jframe){
      this.jframe1 = jframe;
   }

   ...
   jframe1.txt1.setText("Hallo!");
   this.dispose();
   .....

}
Was it helpful?

Solution

There are too many ways,

One of those is provide a constructor to your frame with String parameter and pass the value.

For example,

public class jFrame1 extends javax.swing.JFrame{

   public JTextField txt1; // Hope you have initialized this somewhere in your code else you will face a NPE.
   private JButton btn1;

   btn1.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
         jFrame2 jframe2 = new jFrame2(this, txt1.getText());
         jframe2.setVisible(true);
      }
   });


   .....

}


public class jFrame2 extends javax.swing.JFrame{

   private JFrame jframe1;
   private String text;
   public JTextField txtDemo; 

   public jFrame2(JFrame jframe){
      this.jframe1 = jframe;
   }

   public jFrame2(JFrame jframe, String text){
      this.jframe1 = jframe;
      txtDemo = new JTextField(text);
   }

   ...

}

You can find answer in this SO question also.

And refer the answer on The Use of Multiple JFrames, Good/Bad Practice? before implementing this, a good explanation on JFrame and Swing is given.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top