单击后如何关闭此JOptionPane?

时间:2014-04-15 23:44:29

标签: java joptionpane

我的JOptionPane显示正常,但是当我点击按钮时,没有任何反应。单击“X”后,控制台将打印单击了哪些按钮。单击按钮时它不会关闭:

final JOptionPane newDocWarning = new JOptionPane("Would you like to save before opening a new file?", JOptionPane.WARNING_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION);
final JDialog newDocDialog = new JDialog(this, "New Document", true);                

newDocDialog.setContentPane(newDocWarning);
newDocDialog.setSize(420, 150);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); 
newDocDialog.setLocation(dim.width/2-newDocDialog.getSize().width/2, dim.height/2- newDocDialog.getSize().height/2);
newDocDialog.setVisible(true);

int value = ((Integer)newDocWarning.getValue()).intValue();

if(value == JOptionPane.YES_OPTION){
    System.out.println("YES OPTION WAS CLICKED");
    newDocDialog.dispose();
}else if(value == JOptionPane.NO_OPTION){
    System.out.println("NO OPTION WAS CLICKED");
    newDocDialog.setVisible(false);
}else if(value == JOptionPane.CANCEL_OPTION){
    System.out.println("CANCEL OPTION WAS CLICKED");
    newDocWarning.setVisible(false);
}

1 个答案:

答案 0 :(得分:4)

您可以使用JOptionPane.showConfirmDialog()

试试这个
int value = JOptionPane.showConfirmDialog(frame,
        "Would you like to save before opening a new file?", "New Document",
        JOptionPane.INFORMATION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION);

在这种情况下,您不需要关闭它。单击任何按钮后,它将自动关闭。

有关详细信息,请查看How to Make Dialogs

enter image description here