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.
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.
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)
whereoptionType
canbe:
Example:
inti=JOptionPane.showConfirmDialog(null,"Deseja continuar?",
"Continua",
JOptionPane.OK_CANCEL_OPTION
);
Result:
Reference: JOptionPane - Java SE 7