How do I handle the JOptionPane.showMessageDialog () options?

1

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

asked by anonymous 07.05.2014 / 16:59

1 answer

1

You should use showConfirmDialog() since showMessageDialog() does not return anything.

The showConfirmDialog() returns an int, store it, and then compare it with the static constants of the JOptionPane class. 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");
}

Result:

Tochangethebuttonsinyourdialog,createtheoverloadedversionshowConfirmDialog(parentComponent,message,title,optionType)whereoptionTypecanbe:

  • DEFAULT_OPTION(althoughthedocumentationdoesnotmakeitclear,it'sOKalone)
  • YES_NO_OPTION
  • YES_NO_CANCEL_OPTION
  • OK_CANCEL_OPTION

Example:

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

Result:

Reference: JOptionPane - Java SE 7

    
07.05.2014 / 17:02