Sorry. it was a bit hard to think of an appropriate title, but hopefully the code is clear enough. Here's my method:
public static String createString(JFrame owner) {
final JDialog jd = new JDialog(owner, true);
final JTextField text = new JTextField();
text.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
synchronized (text) {
text.notify();
}
jd.dispose();
}
});
jd.setSize(300, 100);
jd.add(text);
jd.setLocationRelativeTo(null);
jd.setVisible(true);
synchronized (text) {
try {
text.wait();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
return text.getText();
}
Basically, I'm trying to create something similar to JOptionPane.showInputDialog(). It works fine when my JDialog is created with modal = false. Like this:
final JDialog jd = new JDialog(owner, false);
But when I set it to true, the thread is never notified on the text's action listener. Like so:
public static void main(String[] args) {
//...
System.out.println(createString(someFrame));
System.out.println("I'm never reached");
}
To sum it up, when the dialog is created with modal set to false, it works fine, it is, read something on a text field, and have the method return it, but when it is set to true, it gets locked forever, is there any reason for that behaviour?
The main thread should wait until the user enter input on the dialog, then the action listener notifies the main thread to stop waiting. But instead it isn't stopping waiting as it should
You cannot do wait/notify on the EDT since all UI actions are processed on a single thread. This is why your UI is locking up. This is not how you get the result of a dialog in swing. instead, your button action should invoke some sort of callback that does whatever you need to happen next (as opposed to "notifying" a waiting thread).