1

I am wondering how you can change something in a parent window using a child window. So, let's say I have a window, that opens a pop-up window on the press of a button. That new window contains a JTextArea and another button called Ok. How can I change the title of the parent window based on what's inside the JTextArea when the Ok button is pressed?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Casteurr
  • 956
  • 3
  • 16
  • 35

1 Answers1

7

The way I see it, there are two common ways to do this:

  • The child window could push the information into the parent window when OK is pressed. For this to occur, the child window would need a reference to the parent window and then call a public method of the parent.
  • The parent window could pull the information from the child. This can occur in one of two ways.
    • If the child window is a modal dialog, then the parent could simply query the child window once the dialog has been dealt with and program flow returns to the parent's code.
    • If the dialog is a non-modal dialog, then the parent window would need to add a listener to the child, say a PropertyChangeListener, and when the appropriate event is triggered by this listener, the parent window would query the dialog window for the information. This would be an example of using the Observer design pattern.

I much prefer the pull technique since because it is the parent that is the object that has code to display the child window and that needs the information from the child window, it should have the code to extract the information needed, and the child window would need to have no knowledge of or reference to the parent window object. This seems much cleaner to me.

For an example of this, please check out my code here, here and here.

Edit: Note that for the example that you described, you could easily solve this by using a JOptionPane. Many don't know that JOptionPanes can display very complex GUI's; basically anything that can be put onto a JPanel can be displayed in a JOptionPane (and then some). You would simply display the JOptionPane that shows your JTextField, and when program flow returns to the calling program, simply get the text held by the JTextField that was displayed in the JOptionPane. Nothing could be simpler.

Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373