Search code examples
javaswingjoptionpane

Figure out when a button is pressed in another window


I run my main window in the main method like this:

SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        NoteSystem MainWindow = new NoteSystem();
        MainWindow.initUI();

    }
});

And then when a button is pressed on this form, I create a window by instantiating a class I made. I'm having trouble detecting when the second form is closed and what the textboxes/other controls contained.

What is the proper way to: a) Fire an event in NoteSystem when the second window is closed b) allow NoteSystem to check all the components/controls in the second window

I considered using a JOptionPane, but I'd like to create the window entirely in my own class. The idea of having the main window frozen while waiting for response from the second window works for my application though, so if I could use JOptionPane with my own class, that would be ideal.

Thanks


Solution

  • The best way is to use a modal dialog, a window like a JFrame, but that halts program flow in the calling code until it is no longer visible. This way, the calling code will know exactly when the dialog window has been dealt with, since its code flow will resume once again, and so often the calling code will extract information from the dialog window code at that point. A JOptionPane is one type of these, and so is a modeal JDialog (of which a JOptionPane is a sub-type). Either of these can display as complex a GUI as any that is displayed within a JFrame, so don't sell them short. You'll notice that the second parameter of most JOptionPane methods is of type Object, meaning anything can go in there, but most often you'll pass in either a String for a simple JOptionPane, or a JPanel that can be chock full of components and other nested JPanels, and in this way the JOptionPane can display the complex GUI if need be.

    For examples, please see: