以编程方式closuresJOptionPane

我正在一个项目中,我想通过编程closures一个通用的JOptionPane(通过不物理地点击任何button)。 当一个计时器到期时,我想closures任何可能打开的JOptionPane,并将用户踢回到我的程序的login屏幕。 我可以把用户踢回去,但是JOptionPane保持不变,除非我物理地点击它上面的一个button。

我看过很多网站没有这样的运气。 在JOptionPane的“Red X”上调用doClick()方法似乎不太可能,并且使用JOptionpane.getRootFrame()。dispose()不起作用。

从技术上讲,你可以遍历应用程序的所有窗口,检查它们是否是JDialogtypes,并且有一个types为JOptionPane的子类,如果是这样的话,

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; } };