-2

I have two JFrame within a project. In JFrame1 I have one JTextField (JFrame1_JTextField) and one Button. In another JFrame I have only one JTextField (JFrame2_JTextField).

When I run the program and enter text in JFrame1_TextField and click the button, I want the text to be displayed in JFrame2_JTextField. But no text is displayed in the second JFrame.

I am not getting any error but I am also not getting the expected output.

Expected output: I want the text entered in JFrame1_JtextField to be set into JFrame2_JTextField after clicking the button.

private void ButtonActionPerformed(java.awt.event.ActionEvent evt) { 
    new JFrame2().JFrame2_JTextField.setText(this.JFrame1_JTextField.getText());
    new JFrame2().setVisible(true);
}                           
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433

1 Answers1

1

Your code creates two new JFrame2s.

new JFrame2().JFrame2_JTextField.setText(this.JFrame1_JTextField.getText());

Here you created a new JFrame2 and set the text content.

new JFrame2().setVisible(true);

Now you create yet another new JFrame2 and show it. The text content has been put in the JFrame2 you created before, so obviously the 2nd JFrame2 can't display it.

Store your JFrame2 in a variable and use that:

JFrame2 jframe2 = new JFrame2();
jframe2.JFrame2_JTextField.setText(this.JFrame1_JTextField.getText());
jframe2.setVisible(true);

Communication via public variables is problematic on it's own, but that wasn't the scope of the question. Still, please consider writing public methods in your JFrame classes that you can use for data exchange.

sina
  • 1,817
  • 1
  • 18
  • 42
  • Thanks a lot for your kind help. – Hemant Lakhotiya Jan 24 '18 at 15:01
  • Glad I could help. Please click the grey check mark next to my answer, in order to inform others that your problem is solved. [How does accepting answers work?](https://meta.stackexchange.com/a/5235) – sina Jan 24 '18 at 15:06