How do I handle Joptionpane.showMessageDialog() options?

Asked

Viewed 5,391 times

2

How do I handle user choices on JOptionPane.showMessageDialog()?
For example, when the user chooses okay the program continues normally if he chooses cancel the program executes another line of code.

1 answer

2


You must use showConfirmDialog() since showMessageDialog() returns nothing.

The showConfirmDialog() return an int, store it and then compare it with the static constants of the class JOptionPane. Example:

int i = JOptionPane.showConfirmDialog(
        null, 
        "Deseja continuar?"
        );
if(i == JOptionPane.YES_OPTION) {
    System.out.println("Clicou em Sim");
}
else if(i == JOptionPane.NO_OPTION) {
    System.out.println("Clicou em Não");
}
else if(i == JOptionPane.CANCEL_OPTION) {
    System.out.println("Clicou em Cancel");
}

Upshot:

selecionar

To change your dialog buttons, create the overloaded version showConfirmDialog(parentComponent, message, title, optionType) where optionType can be:

  • DEFAULT_OPTION (although the documentation does not make it clear, is OK alone)
  • YES_NO_OPTION
  • YES_NO_CANCEL_OPTION
  • OK_CANCEL_OPTION

Example:

int i = JOptionPane.showConfirmDialog(
        null, 
        "Deseja continuar?",
        "Continua",
        JOptionPane.OK_CANCEL_OPTION
        );

Upshot:

OkCancel

Reference: Joptionpane - Java SE 7

Browser other questions tagged

You are not signed in. Login or sign up in order to post.