问题
I'm using NetBeans.
My JFrame
has as default close operation: EXIT_ON_CLOSE
.
I have a button that is supposed to close the program on this JFrame
, this is the action performed code:
private void bSalirActionPerformed(java.awt.event.ActionEvent evt){
this.dispose();
}
I thought this would close all the JFrame
s of the program but it doesn't, could you explain me why or how to fix it?
回答1:
If you want to exit your application with the button than you can use System.exit()
or frame.dispose()
.
but be careful with System.exit()
as this will terminate the JVM
.
So it is better to first confirm from user before this.
with JOptionPane.showConfirmDialog()
;
private void bSalirActionPerformed(java.awt.event.ActionEvent evt){
int exit = JOptionPane.showConfirmDialog(
frame,
"Are you sure you want to exit the application?",
"Exit Application",
JOptionPane.YES_NO_OPTION);
if(JOptionPane.YES_OPTION == exit){
frame.dispose(); // or System.exit(1);
}
}
回答2:
Assuming you called your JFrame frame, like this:
JFrame frame = new JFrame();
You can close it by calling
frame.dispose();
Also, calling this.dispose() refers to the dispose() method that you defined in your class. This is probably why it isn't working. Do you have a method in your class that is called dispose? If so, what exactly does this method do?
回答3:
EXIT_ON_CLOSE
That is what happens when you click the "X" button on the top right of the frame.
Your ActionListener is invoking dispose() on the current frame. If this is the only open frame then the application will also close, but the dispose method does not close all open frame/dialogs.
Check out Closing an Application. You can use the ExitAction
for your button if you want to close the entire application since it will simulate a user clicking on the "X" button.
回答4:
Call frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE) when constructing the frame. In the actionPerformed
method, call frame.dispose() & the JVM should end as long as there are no other non-daemon threads running.
DISPOSE_ON_CLOSE
can be seen in a short demo. on this answer.
..I thought this would close all the jFrames..
There should only be one (despite the above screen-shot, given it is an artificial situation). See The Use of Multiple JFrames, Good/Bad Practice? The above demo will close after the 3rd frame is closed.
回答5:
I use below method, simply call this mesthod, it will close the current window/jFrame :
private void close(){
WindowEvent windowEventClosing = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(windowEventClosing);
}
Also set 'defaultCloseOperation' for jFrame in properties, according to your need.
来源:https://stackoverflow.com/questions/19670454/default-close-operation-of-a-jframe-isnt-working