Domanda

My JOptionPane shows up just fine, but when I click the button, nothing happens. Once I click the 'X', the console will print which of the buttons was clicked. It just won't close when the button is clicked:

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);
}
È stato utile?

Soluzione

Can you try this one using 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);

In this case you don't need to close it. It will be automatically closed once any button is clicked.

For more info have a look at How to Make Dialogs.

enter image description here

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top