java 关闭jpanel_Java中的关闭窗口(JPanel)

小编典典

获取顶层窗口:

public void actionPerformed(ActionEvent e) {

JComponent comp = (JComponent) e.getSource();

Window win = SwingUtilities.getWindowAncestor(comp);

win.dispose();

}

确保已将JFrame的默认关闭操作设置为JFrame.DISPOSE_ON_CLOSE(首选)或JFrame.EXIT_ON_CLOSE(首选)。

如果有可能会从JMenuItem调用此方法,那么除非您首先测试组件的父级是JPopupMenu还是JToolBar,否则它将不起作用。如果是这样,那么您应该使用更健壮的解决方案,例如可以在java-

swing-tips上找到,特别是以下代码:

class ExitAction extends AbstractAction {

public ExitAction() {

super("Exit");

}

@Override public void actionPerformed(ActionEvent e) {

JComponent c = (JComponent) e.getSource();

Window window = null;

Container parent = c.getParent();

if (parent instanceof JPopupMenu) {

JPopupMenu popup = (JPopupMenu) parent;

JComponent invoker = (JComponent) popup.getInvoker();

window = SwingUtilities.getWindowAncestor(invoker);

} else if (parent instanceof JToolBar) {

JToolBar toolbar = (JToolBar) parent;

if (((BasicToolBarUI) toolbar.getUI()).isFloating()) {

window = SwingUtilities.getWindowAncestor(toolbar).getOwner();

} else {

window = SwingUtilities.getWindowAncestor(toolbar);

}

} else {

Component invoker = c.getParent();

window = SwingUtilities.getWindowAncestor(invoker);

}

if (window != null) {

//window.dispose();

window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING));

}

}

}

2020-11-23

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值