问题
My current design is like this: I have an outer frame that displays main app. When user clicks a button on the main app, a pop-up Window should be launched. I am using JOptionPane.showInternalOptionDialog and passing button objects as options. When user clicks one of these button, it should run certain commands and then close the window. I was not able to close the Frame that shows the pop-up.
I found a similar question in this forum, that suggests the following workaround. Closing a dialog created by JOptionPane.showOptionDialog()
But the above workaround closes my complete gui. I just want to close the JOptionPane popup.
Thanks in advance.
回答1:
try
JOptionPane.getRootFrame().dispose();
in a event
回答2:
A couple of solutions:
- Create a JOptionPane directly instead of using the showX() methods. This will allow you to have a reference to the dialog that you can pass to your button to allow it to call the dispose method().
- Create your own dialog instead of using JOptionPane. This would be my preferred option, seeing that you are starting to get away from a simple dialog.
回答3:
I had the same problem. I solve it using a thread that close my JOptionPane after X milliseconds.
import javax.swing.JOptionPane;
public class JOptionPaneExample {
public static void main(String[] args) {
final JOptionPane pane =new JOptionPane();
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
pane.getRootFrame().dispose();
}
});
t1.start();
pane.showMessageDialog(null, "I will close after 3000 milli's", "Programmatic Auto-close JOptionPane", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
回答4:
By default, clicking a button in a JOptionPane
will close the dialog. If yours doesn't, it's because you are using actual components rather than strings or other objects, and it is calling your buttons' custom event handlers instead of its own.
I would recommend you take a different approach, using strings instead of buttons. Use an array of buttons as your input values, and when the call to showInternalOptionDialog
returns, you can check the int index to find out what was pressed, and then switch on it in your code. This way, you don't have to touch the JOptionPane
at all and it will close by itself.
来源:https://stackoverflow.com/questions/5408528/closing-joptionpane-showinternaloptiondialog-programmatically