我对joptionpane有疑问。
使用JOptionPane.showMessageDialog(...),我们可以创建一个消息对话框。但是如何以编程方式关闭它?
答案 0 :(得分:21)
你总是可以通过获取它所持有的任何组件的WindowAncestor来获得对JOptionPane的引用,然后在返回的Window上调用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();
}
});
}
}