ITeye博客

NetBeans的关闭退出事件

xbgd · 2010-11-15 22:55 · NetBeans · 编程语言 · 算法 · 工作 · Netbeans · 框架 · Markdown

实现Application.ExitListener接口,它可以允许你否决或者同意退出操作。默认的exit算法会在调用shutdown方法之前先查看所有的listener. 通过实现ExitListener接口,你可以提醒你的客户程序正在退出,并且还可以允许他们取消关闭操作。

ExitListener接口有两个方法

Public Boolean canExit(EventObject e)

Public void willExit(EventObject e)

使用canExit方法去回答退出请求。它返回一个true代表可以退出,返回一个false代表不可以退出。willExit方法仅仅起提示作用,但你也可以用它来执行一些退出前的准备工作。

示例5向你展示了如何实现ExitListener。请注意,例子调用了exit方法,它是在Application类中实现的了。Exit方法会提醒所有的ExitListener对象,如果所有的listener都同意退出,框架会调用shutdown方法最终关闭程序。

public class ConfirmExit extends SingleFrameApplication { 2 3 private JButton exitButton; 4 5 6 7 @Override 8 9 protected void startup() { 10 11 getMainFrame().setTitle("ConfirmExit"); 12 13 exitButton = new JButton("Exit Application"); 14 15 exitButton.addActionListener(new ActionListener() { 16 17 public void actionPerformed(ActionEvent e) { 18 19 exit(e); 20 21 } 22 23 24 25 }); 26 27 addExitListener(new ExitListener() { 28 29 public boolean canExit(EventObject e) { 30 31 boolean bOkToExit = false; 32 33 Component source = (Component) e.getSource(); 34 35 bOkToExit = JOptionPane.showConfirmDialog(source, 36 37 "Do you really want to exit?") == 38 39 JOptionPane.YES_OPTION; 40 41 return bOkToExit; 42 43 } 44 45 public void willExit(EventObject event) { 46 47 48 49 } 50 51 }); 52 53 show(exitButton); 54 55 } 56 57 58 59 @Override 60 61 protected void shutdown() { 62 63 // The default shutdown saves session window state. 64 65 super.shutdown(); 66 67 // Now perform any other shutdown tasks you need. 68 69 // 70 71 } 72 73 74 75 /** //* 76 77 * @param args the command-line arguments 78 79 */ 80 81 public static void main(String[] args) { 82 83 Application.launch(ConfirmExit.class, args); 84 85 } 86 87 88 89}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。