我想關閉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