用到JOptionPane.showConfirmDialog方法,showConfirmDialog 的返回类型是int,定义一个int类型的变量接收返回值,然后根据业务逻辑判断,代码看不懂,可以自行百度搜索或问同事,编程注重思想。
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class JButtonTest extends JFrame
{
public static void main ( String[] args )
{
JButtonTest b = new JButtonTest ();
b.addWindowListener (new WindowAdapter ()
{
@Override
public void windowClosing ( WindowEvent e )
{
int exi = JOptionPane.showConfirmDialog (null, "要退出该程序吗?", "友情提示", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (exi == JOptionPane.YES_OPTION)
{
System.exit (0);
}
else
{
return;
}
}
});
b.setSize (300, 300);
b.setLocationRelativeTo (null);
b.setDefaultCloseOperation (JFrame.DO_NOTHING_ON_CLOSE);
b.setVisible (true);
}
}
给整个JFrame添加个监视器
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
int ret = JOptionPane.showConfirmDialog(null, "确定不玩了吗?","Attention",JOptionPane.OK_OPTION);
if(ret==JOptionPane.OK_OPTION)
System.exit(0);
}
});
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class JButtonTest extends JFrame
{
public static void main ( String[] args )
{
JButtonTest b = new JButtonTest ();
b.addWindowListener (new WindowAdapter ()
{
@Override
public void windowClosing ( WindowEvent e )
{
int exi = JOptionPane.showConfirmDialog (null, "确定不玩了么?", "友情提示", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (exi == JOptionPane.YES_OPTION)
{
System.exit (0);
}
else
{
return;
}
}
});
b.setSize (300, 300);
b.setLocationRelativeTo (null);
b.setDefaultCloseOperation (JFrame.DO_NOTHING_ON_CLOSE);
b.setVisible (true);
}
}