Java中的关闭窗口(JPanel) [英] Close Window (JPanel) in Java
问题描述
我添加了一个添加到JPanel的JTabbedPane的Button,其中包含以下内容:
I have a Button added to a JTabbedPane added to a JPanel with something like this:
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));
}
});
但它给了我
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: null source
如何关闭按钮上的窗口按
How do I close the Window on Button Press
推荐答案
获取顶级窗口:
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
(不是首选)。
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).
如果有可能从JMenuItem调用它,那么除非你首先测试comp的父级是JPopupMenu还是JToolBar,否则它将无法工作。如果是这样,那么您应该使用更强大的解决方案,例如可以在 java-swing-tips ,特别是这段代码:
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. If so, then you should use a more robust solution such as can be found at java-swing-tips, specifically this code:
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));
}
}
}
这篇关于Java中的关闭窗口(JPanel)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!