[英]Close Window (JPanel) in Java
I have a Button added to a JTabbedPane added to a JPanel with something like this: 我有一个按钮添加到JTabbedPane添加到JPanel与这样的事情:
JTabbedPane tabbedPane = new JTabbedPane();
JButton btnClose = new JButton("Close");
JComponent panel.add(btnClose);
tabbedPane.addTab("Test", panel);
I want to close the window on the button press. 我想在按钮按下时关闭窗口。 I tried do this: 我尝试这样做:
btnClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
panel.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
}
});
But it gives me 但这给了我
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: null source
How do I close the Window on Button Press 我如何在按下按钮时关闭窗口
Get the top level window: 获取顶层窗口:
public void actionPerformed(ActionEvent e) {
JComponent comp = (JComponent) e.getSource();
Window win = SwingUtilities.getWindowAncestor(comp);
win.dispose();
}
Make sure that the JFrame's default close operation has been set to JFrame.DISPOSE_ON_CLOSE
(preferred) OR JFrame.EXIT_ON_CLOSE
(not preferred). 确保已将JFrame的默认关闭操作设置为JFrame.DISPOSE_ON_CLOSE
(首选)或JFrame.EXIT_ON_CLOSE
(首选)。
If there is ever a chance that this will be called from a JMenuItem, then it will not work unless you first test if the comp's parent is either a JPopupMenu or a JToolBar. 如果有可能会从JMenuItem调用此方法,那么除非您首先测试组件的父级是JPopupMenu还是JToolBar,否则它将不起作用。 If so, then you should use a more robust solution such as can be found at java-swing-tips , specifically this code: 如果是这样,那么您应该使用更健壮的解决方案,例如可以在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));
}
}
}
source: WindowClosingAction 来源: WindowClosingAction
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.