To display a confirmation dialog in Java, you can use the showConfirmDialog
method of the JOptionPane
class. This method displays a modal dialog with a message and a set of buttons (such as "Yes", "No", and "Cancel"), and returns an integer value indicating which button was clicked.
Here is an example of how you can use the showConfirmDialog
method to display a confirmation dialog in Java:
import javax.swing.JOptionPane; public class Main { public static void main(String[] args) { int option = JOptionPane.showConfirmDialog(null, "Are you sure you want to do this?", "Confirmation", JOptionPane.YES_NO_CANCEL_OPTION); if (option == JOptionPane.YES_OPTION) { // The user clicked the "Yes" button System.out.println("User clicked Yes"); } else if (option == JOptionPane.NO_OPTION) { // The user clicked the "No" button System.out.println("User clicked No"); } else if (option == JOptionPane.CANCEL_OPTION) { // The user clicked the "Cancel" button System.out.println("User clicked Cancel"); } } }
In this example, we use the showConfirmDialog
method to display a confirmation dialog with a message and three buttons ("Yes", "No", and "Cancel"). The method returns an integer value indicating which button was clicked, which we can check using the constants YES_OPTION
, NO_OPTION
, and CANCEL_OPTION
.