java组件的事件如何激活

本文介绍了一个常见问题:在使用Java AWT/Swing时,如何确保窗口的关闭事件能够正确触发。通过实例演示了如何手动激活窗口事件,从而使窗口响应关闭操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  有的时候经常会发生在组件中增加监听器之后,监听器并没有收到事件,解决方法有2种,第一种是将监听器增加到顶层容器中,这样时间就有效了,但我今天说的是第二种,将组件中的事件激活。
  看第一代码: import java.awt.Frame; import java.awt.event.WindowEvent; import javax.swing.WindowConstants; @SuppressWarnings("serial") public class WindowEventsSample extends Frame implements WindowConstants { private int defaultCloseOperation = EXIT_ON_CLOSE; public WindowEventsSample() { super(); setSize(800, 600); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { new WindowEventsSample(); } @Override protected void processWindowEvent(WindowEvent e) { super.processWindowEvent(e); if (e.getID() == WindowEvent.WINDOW_CLOSING) { switch (defaultCloseOperation) { case HIDE_ON_CLOSE: setVisible(false); break; case DISPOSE_ON_CLOSE: dispose(); break; case DO_NOTHING_ON_CLOSE: default: break; case EXIT_ON_CLOSE: System.exit(0); break; } } } public void setDefaultCloseOperation(int operation) { if (operation != DO_NOTHING_ON_CLOSE && operation != HIDE_ON_CLOSE && operation != DISPOSE_ON_CLOSE && operation != EXIT_ON_CLOSE) { throw new IllegalArgumentException("defaultCloseOperation must be one of: DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE, DISPOSE_ON_CLOSE, or EXIT_ON_CLOSE"); } if (this.defaultCloseOperation != operation) { if (operation == EXIT_ON_CLOSE) { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkExit(0); } } int oldValue = this.defaultCloseOperation; this.defaultCloseOperation = operation; firePropertyChange("defaultCloseOperation", oldValue, operation); } } public int getDefaultCloseOperation() { return defaultCloseOperation; } } 运行上边的代码,我们发现无论我们操作都不能关闭窗口,这里也是为什么我们说用Frame而不是JFrame,呵呵,JFrame已经将这一步做好了,原因是该组件的WindowEvent并没有被激活,看下边第二段代码: public WindowEventsSample() { super(); // 激活组件的按键、窗口、鼠标事件 enableEvents(AWTEvent.KEY_EVENT_MASK | AWTEvent.WINDOW_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK); setSize(800, 600); setLocationRelativeTo(null); setVisible(true); }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值