10
我有一個關於joptionpane的問題。如何以編程方式關閉消息對話框?
使用JOptionPane.showMessageDialog(...),我們可以創建一個消息對話框。但如何以編程方式關閉它?
我有一個關於joptionpane的問題。如何以編程方式關閉消息對話框?
使用JOptionPane.showMessageDialog(...),我們可以創建一個消息對話框。但如何以編程方式關閉它?
您可以通過獲取任何組件的WindowAncestor來獲取對JOptionPane的引用,然後在返回的窗口上調用dispose()
或setVisible(false)
。該窗口可以通過使用SwingUtilities.getWindowAncestor(component)
來獲得。例如:
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class CloseOptionPane {
@SuppressWarnings("serial")
private static void createAndShowGui() {
final JLabel label = new JLabel();
int timerDelay = 1000;
new Timer(timerDelay , new ActionListener() {
int timeLeft = 5;
@Override
public void actionPerformed(ActionEvent e) {
if (timeLeft > 0) {
label.setText("Closing in " + timeLeft + " seconds");
timeLeft--;
} else {
((Timer)e.getSource()).stop();
Window win = SwingUtilities.getWindowAncestor(label);
win.setVisible(false);
}
}
}){{setInitialDelay(0);}}.start();
JOptionPane.showMessageDialog(null, label);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
沒有什麼比完美更.... – 2012-03-25 14:22:17
有人可以從這個扣分,大聲笑,我不這麼認爲+1這個精心設計的例子:-) – 2012-03-25 14:23:03
謝謝。但關鍵是在顯示JOptionPane之前調用所有必要的代碼。 – 2012-03-25 14:24:58