问题
I have a showOptionDialog that ask if the user wants to delete something. I want to close the frame and not delete if nothing is press after 5 seconds. How can I achive this?
Here is my code:
JFrame frame = new JFrame();
frame.setAlwaysOnTop(true);
Object[] options = {"OK"};
int n = JOptionPane.showOptionDialog(frame,"Do you want to delete?","Title",JOptionPane.PLAIN_MESSAGE,JOptionPane.QUESTION_MESSAGE,null,options,options[0]);
if (JOptionPane.OK_OPTION == n) {
System.out.println("Delete");
} else {
System.out.println("Not Delete");
}
回答1:
Read the JOptionPane API
. There is a section on "Direct Use"
of the JOptionPane.
You will need to create the option pane and dialog manually. When you do this you will now have a reference to the dialog used by the option pane, which means you can dispose() of the dialog if it is still open.
So you will also need to create a Swing Timer. When the timer fires you use dialog.dispose()
.
You would need to start the Timer BEFORE the dialog is made visible.
Also, before you check the return value from the option pane you would want to stop the Timer, since you don't want the Timer to fire when the option pane is already closed.
So the basic logic (taken from the API) would be:
JOptionPane pane = new JOptionPane(arguments);
pane.set.Xxxx(...); // Configure
JDialog dialog = pane.createDialog(parentComponent, title);
Timer timer = new Timer(5000, (e) -> dialog.dispose());
timer.start();
dialog.setVisible(true);
timer.stop();
...
Edit:
I change it to:
JOptionPane pane = new JOptionPane(
"Do you want to delete?",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.ERROR_MESSAGE,
null,
options,
options[0]);
I can see so many problems with the above statement:
Why are you using that constructor? Why are you passing so many null parameters? As I mentioned in my earlier comment there are simpler constructors to use.
Why are you specifying the "option type" before the "message type". Did you read the API? Can you show me a constructor where this is valid?
3 . Why are you using JOptionPane.ERROR_MESSAGE
? This is a question? Should you not be using JOptionPane.QUESTION_MESSAGE
?
Did you even read the API like I suggested? You can't program if you don't read the API and understand what the different constructors and methods are.
it returns an integer, but in this case where can I see it?
It may or may not return an integer depending on how the dialog was closed. If you click a button it will be an integer. If the Timer fires it will be a String.
Again, did you read the section from the API on Direct Use
? It shows you how to get the value returned from the option pane and check it's value.
So once again I ask, did you read the API? Is there something about the code presented in the API that you don't understand. If so ask a specific question.
来源:https://stackoverflow.com/questions/52630390/close-showoptiondialog-after-5-seconds-if-not-button-is-pressed-in-java