class MyWindowAdapter extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
int flag = JOptionPane.showConfirmDialog(MainFrame.this, "Are you sure that you want to exit? " +
"Any unsaved work will be lost! ", "Sure to exit?", JOptionPane.YES_NO_OPTION);
if (flag == 0) // User selected YES
setVisible(false);
else if (flag == 1) // User selected NO
// ...
}
}
addWindowListener(new MyWindowAdapter());如果用户点击左上角的那个小叉,就会弹出我定义的那个confirmDialog,但是不管我选YES还是NO,窗口最后都会关闭。有什么办法可以让这个Frame在选择NO后不关闭?
{
public void windowClosing(WindowEvent e)
{
int flag = JOptionPane.showConfirmDialog(MainFrame.this, "Are you sure that you want to exit? " +
"Any unsaved work will be lost! ", "Sure to exit?", JOptionPane.YES_NO_OPTION);
if (flag == 0) // User selected YES
setVisible(false);
else if (flag == 1) // User selected NO
// ...
}
}
addWindowListener(new MyWindowAdapter());如果用户点击左上角的那个小叉,就会弹出我定义的那个confirmDialog,但是不管我选YES还是NO,窗口最后都会关闭。有什么办法可以让这个Frame在选择NO后不关闭?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;public class Test extends JFrame
{
public Test()
{
setSize(200, 200);
addWindowListener(new MyWindowAdapter());
}
public static void main(String[] args)
{
Test t = new Test();
t.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);//你肯定落了这句
t.setVisible(true);
}
class MyWindowAdapter extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
int flag = JOptionPane.showConfirmDialog(Test.this, "Are you sure that you want to exit? " +
"Any unsaved work will be lost! ", "Sure to exit?", JOptionPane.YES_NO_OPTION);
if (flag == JOptionPane.YES_OPTION)
Test.this.setVisible(false);
}
}
}