步骤
- 先设置DO_NOTHING_ON_CLOSE:
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
。
- 然后再调用frame.addWindowListener方法,重写windowClosing方法,在windowClosing方法里面弹出确认对话框。
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import javax.swing.*; import java.awt.event.*; public class CloseConfirmation { public static void main(String[] args) { JFrame frame = new JFrame("Close Confirmation Example"); frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { int confirm = JOptionPane.showConfirmDialog(frame, "Are you sure you want to close?"); if (confirm == JOptionPane.YES_OPTION) { frame.dispose(); } } }); frame.setVisible(true); } }
|
示例2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| private void frameSettings() { frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { int result = JOptionPane.showConfirmDialog(contentPane, "确定关闭", "是否关闭窗体", JOptionPane.YES_NO_OPTION);
switch (result) { case JOptionPane.OK_OPTION: super.windowClosing(e); universalPanels.getBtnStop().doClick(); scrcpyJPanels.getBtnKillScrcpy().doClick(); System.out.println("窗体正在关闭。。。。。。。。。。。。"); System.exit(0); break; } } }); frame.setAlwaysOnTop(true); frame.pack(); frame.setVisible(true); }
|