2
我有簡單的Java Swing應用程序。我想在關閉主窗口之前得到用戶的確認。Swing addWindowFocusListener
有我的代碼:
package client_interface;
import java.awt.EventQueue;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class MainWindow {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MainWindow() {
initialize();
}
private void setFrameSize(JFrame frame) {
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
int width = gd.getDisplayMode().getWidth();
int height = gd.getDisplayMode().getHeight();
frame.setBounds(new Rectangle(width/4, height/4, width/2, height/2));
//frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
private void initialize() {
frame = new JFrame("Test");
setFrameSize(frame);
frame.addWindowFocusListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
if (JOptionPane.showConfirmDialog(frame,
"Are you sure to close this window?", "Really Closing?",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION){
System.exit(0);
}
}
});
}
}
但目前看來,frame.addWindowFocusListener不起作用。
請告訴我正確的方法添加事件windowClosing到我的框架。
你是什麼意思得到用戶的確認?你的意思是想要彈出一個窗口詢問用戶是否確定要關閉? – DreadHeadedDeveloper 2014-10-27 17:55:28
是的。我想要確認窗口在關閉主窗口之前彈出 – 2014-10-27 17:57:17