我有一个java应用程序,想要关闭带有确认窗口的GUI来关闭应用程序
例如: -
frmViperManufacturingRecord.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frmViperManufacturingRecord.addWindowListener( new WindowAdapter(){
public void windowClosing(WindowEvent e){
JFrame frame = (JFrame)e.getSource();
int result = JOptionPane.showConfirmDialog(frame, "Are you sure you want to close the application?", "Please Confirm",JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
这是正常工作fine,当我按下窗口关闭(x)按钮,但我想将此事件带到一个按钮以执行操作' On Click&#39 ;,因为我是新手发现困难将其带入“行动表现”'
到目前为止,我已经尝试过以下代码并且它没有工作......
//close window button
JButton btnCloseWindow = new JButton("Close Window");
btnCloseWindow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//frmViperManufacturingRecord.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frmViperManufacturingRecord.dispose();
//System.exit(0);
JFrame frame = (JFrame)e.getSource();
int result = JOptionPane.showConfirmDialog(frame, "Are you sure you want to close the application?", "Please Confirm",JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
请给我一些指示,谢谢
答案 0 :(得分:3)
改变这个:
if (result == JOptionPane.YES_OPTION)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
到
if (result == JOptionPane.YES_OPTION)
System.exit(0);
}
frame.setDefaultCloseOperation
当有人点击' x'关上窗户。退出的其他方式由您控制。最好的方法是让你的窗口关闭监听器和动作监听器调用相同的方法,该方法将弹出对话框并在用户想要退出时调用System.exit(0)
。这也将帮助您进行清理操作。
示例代码:
public class Test extends JPanel implements WindowListener {
public Test() {
setLayout(new BorderLayout());
add(new JLabel("This is a test."), BorderLayout.CENTER);
JButton b = new JButton("Exit");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
exit();
}
});
add(b, BorderLayout.SOUTH);
}
public static void main(String[] args) throws Exception {
JFrame f = new JFrame();
Test t = new Test();
f.add(t, BorderLayout.CENTER);
f.addWindowListener(t);
f.pack();
f.setVisible(true);
}
public void windowClosing(WindowEvent e) {
exit();
}
private void exit() {
System.exit(0);
}
}
答案 1 :(得分:1)
您可以尝试:
if (result == JOptionPane.YES_OPTION){
frame.dispose();
}
另请注意第122行的CastException。
而不是
JFrame frame = (JFrame)e.getSource();
更改为:
JFrame frame = new JFrame();
答案 2 :(得分:1)
如果仍然无效,请尝试
frame.setVisible(false);
frame.dispose();
in if(result == JOptionPane.YES_OPTION){} block