Use anything for setDefaultCloseOperation
excepting EXIT_ON_CLOSE
.
Then, for the cancel button, just dispose()
the window. If the application has another running thread, it won't exit. You can also hide a window by calling setVisible(false)
.
Вопрос
is there any way to close the frame using Cancel button without exiting the whole application. I tried Following
setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE);
above line works only in case when i press X close button to close the frame. Is there any other good way to implement a JButton to perform the same operation
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class CloseTestForm extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CloseTestForm frame = new CloseTestForm();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public CloseTestForm() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnSave = new JButton("Save");
btnSave.setBounds(64, 141, 89, 23);
contentPane.add(btnSave);
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//??
}
});
btnCancel.setBounds(64, 192, 89, 23);
contentPane.add(btnCancel);
}
}
Решение
Use anything for setDefaultCloseOperation
excepting EXIT_ON_CLOSE
.
Then, for the cancel button, just dispose()
the window. If the application has another running thread, it won't exit. You can also hide a window by calling setVisible(false)
.
Другие советы
Call Window.dispose()
to get rid of a frame.
You have to add the button and add an actionListener on the button. Then in the actionPerformed
method of that action listener, call the .dispose()
method on the frame you want to get rid of.
don't extends JFrame
, create that as local variable
then you can to call myFrame.setVisible(false)
in this form (code posted here) current JVM never will be expired, untill PC restarted or turned off
don't create second or more JFrame
s, use JDialog instead