JOptionPane: showConfirmDialog
The method joptionpane.showConfirmDialog() Creates a small confirmation window represented in a dialog box asking the user to confirm their choice. For example, a dialog box with two buttons "yes" and "no".int return = showConfirmDialog(parent, message, title, typeOption, typeMessage), or:
- parent: is the window from which the call is made;
- message: the message to be displayed in the dialog box;
- title: the title of the dialog box;
- typeOption: the option that will display the "Yes", "No", "Ok" and "Cancel" buttons: YES_NO_OPTION, YES_NO_CANCEL_OPTION, and OK_CANCEL_OPTION;
- typeMessage: the message type and icon, the types are: INFORMATION_MESSAGE, WARNING_MESSAGE, ERROR_MESSAGE, and PLAIN_MESSAGE.
This method is a function that returns an integer which is the choice made by the user. Here's an example that shows how to use the showConfirmDialog():
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class MessageDialog {
public static void main(String[] args) {
JFrame window = new JFrame();
window.setLocationRelativeTo(null);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
JButton leave = new JButton("Exit");
window.add(exit);
exit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
int return = showConfirmDialog();
if(return==0)//if the button clicked is "yes"
System.exit(0);
}
});
window.add(exit);
window.pack();
}
static int showConfirmDialog(){
return JOptionPane.showConfirmDialog(
null,
"Are you sure you want to quit?",
"Exit",
JOptionPane.YES_NO_OPTION);
}
}
Result:
If you click "Yes", the program ends by calling the method System.exit(0), otherwise no event will occur when you click the "No" button.
References:
Java2s: Create a Confirm Dialog Box : JOptionPane Dialog
Java Doc: showConfirmDialog method
If you click "Yes", the program ends by calling the method System.exit(0), otherwise no event will occur when you click the "No" button.
References:
Java2s: Create a Confirm Dialog Box : JOptionPane Dialog
Java Doc: showConfirmDialog method