很基础的功能,不过我很少做GUI,所以特意自己留个记录。呵呵!也许大家早就知道怎么做了。
效果如下:
源代码:
效果如下:
源代码:
- import java.awt.event.WindowAdapter;
- import java.awt.event.WindowEvent;
- import javax.swing.JDialog;
- import javax.swing.JFrame;
- import javax.swing.JOptionPane;
- /**
- * 关闭窗口时,询问是否关闭。
- *
- * @author 赵学庆,Java世纪网(java2000.net)
- *
- */
- public class T extends JFrame {
- T() {
- this .setBounds( 100 , 100 , 300 , 200 );
- addWindowListener( new WindowAdapter() {
- public void windowClosing(WindowEvent e) {
- exit();
- }
- });
- }
- public static void main(String[] args) {
- T t = new T();
- t.setVisible( true );
- }
- public void exit() {
- Object[] options = { "确定" , "取消" };
- JOptionPane pane2 = new JOptionPane( "真想退出吗?" , JOptionPane.QUESTION_MESSAGE,
- JOptionPane.YES_NO_OPTION, null , options, options[ 1 ]);
- JDialog dialog = pane2.createDialog( this , "警告" );
- dialog.setVisible( true );
- Object selectedValue = pane2.getValue();
- if (selectedValue == null || selectedValue == options[ 1 ]) {
-
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // 这个是关键
- } else if (selectedValue == options[ 0 ]) {
- setDefaultCloseOperation(EXIT_ON_CLOSE);
- }
- }
- }