我想关闭JOptionPane
后,经过一段时间,我曾尝试与dispose()
,hide()
,并且使用命令getRootPane().dispose()
没有结果。如何自动关闭JOptionPane?
我想在3秒或更长时间后关闭它,以便用户在任何时候都不需要按下按钮,即可出现JOptionPane
。
我想关闭JOptionPane
后,经过一段时间,我曾尝试与dispose()
,hide()
,并且使用命令getRootPane().dispose()
没有结果。如何自动关闭JOptionPane?
我想在3秒或更长时间后关闭它,以便用户在任何时候都不需要按下按钮,即可出现JOptionPane
。
您可以使用这些语句之一来隐藏/关闭JFrame。
Frame.setVisible(false);
或
jFrame.dispose();
即
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setContentPane(new JOptionPane());
frame.setVisible(true);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
Thread.sleep(5000); //sleep 5 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
frame.setVisible(false);
}
您可以循环在活动窗口的类创建这种方法,你想这样做:
private Timer createTimerClose(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;
}
而且之后你可以打电话给metod cre ateTimerClose(secondsyouwanttoclose)。开始();在调用你的JOptionPane之前。
我认为这个问题的关键是'JOptionPane'。此外,你的例子是违反了Swing的单线程规则,从EDT的上下文之外修改UI。例如,如果您在“ActionListener”的上下文中尝试了此操作,则无法按预期工作 – MadProgrammer