问题描述
我正在开发一个项目,我希望以编程方式关闭通用的JOptionPane(通过不点击任何按钮)。当计时器到期时,我想关闭任何可能打开的可能的JOptionPane并将用户踢回我的程序的登录屏幕。我可以很好地踢回用户,但除非我实际点击它上面的按钮,否则JOptionPane仍然存在。
I am working on a project in which I would like to close a generic JOptionPane programmatically (by not physically clicking on any buttons). When a timer expires, I would like to close any possible JOptionPane that may be open and kick the user back to the login screen of my program. I can kick the user back just fine, but the JOptionPane remains unless I physically click a button on it.
我看过许多没有运气的网站。似乎不可能在JOptionPane的Red X上调用doClick()方法,并且使用JOptionpane.getRootFrame()。dispose()不起作用。
I have looked on many sites with no such luck. A doClick() method call on the "Red X" of the JOptionPane does not seem possible, and using JOptionpane.getRootFrame().dispose() does not work.
推荐答案
从技术上讲,你可以循环遍历应用程序的所有窗口,检查它们是否为JDialog类型并且有一个JOptionPane类型的子节点,如果是这样,则处理对话框:
Technically, you can loop through all windows of the application, check is they are of type JDialog and have a child of type JOptionPane, and dispose the dialog if so:
Action showOptionPane = new AbstractAction("show me pane!") {
@Override
public void actionPerformed(ActionEvent e) {
createCloseTimer(3).start();
JOptionPane.showMessageDialog((Component) e.getSource(), "nothing to do!");
}
private Timer createCloseTimer(int seconds) {
ActionListener close = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Window[] windows = Window.getWindows();
for (Window window : windows) {
if (window instanceof JDialog) {
JDialog dialog = (JDialog) window;
if (dialog.getContentPane().getComponentCount() == 1
&& dialog.getContentPane().getComponent(0) instanceof JOptionPane){
dialog.dispose();
}
}
}
}
};
Timer t = new Timer(seconds * 1000, close);
t.setRepeats(false);
return t;
}
};
这篇关于以编程方式关闭JOptionPane的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!