I have a program with a GUI that needs to open a separate window and wait for the user to select and option, then continue. I figure I should be doing this with the wait() and notify() methods, but I'm still trying to figure out exactly how to use those. A complicating factor is that things seem to work differently when the second window is created in an actionPerformed() method, which it needs to be.
Here's how I think it should be done here, apparently it is not quite right...
This should create a window with a button, when the button is pressed, another window with a button should be created, and when that button is pressed, the program should print "End".
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class WtfExample {
public static void main(String[] args) {
JFrame jf = new JFrame();
JButton butt = new JButton("Button");
butt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
WtfExample we = new WtfExample();
we.display();
}
});
jf.getContentPane().add(butt);
jf.setSize(new Dimension(1000, 500));
jf.setVisible(true);
System.out.println("End");
}
public synchronized void display() {
JFrame jf = new JFrame();
JButton butt = new JButton("Button");
butt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
synchronized(WtfExample.this) {
WtfExample.this.notifyAll();
}
}
});
jf.getContentPane().add(butt);
jf.setSize(new Dimension(1000, 500));
jf.setVisible(true);
while(true) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
}
}
edit- I wasn't clear enough in one thing- the second window that's opened is blank, like its components were never added to it. That's the case whether it's a frame or dialog, but that only happens if the window is created from the actionPerformed method.