This section provides a tutorial example on how to use the static method, showConfirmDialog(), to create and display confirmation dialog boxes and receive input code to know which button was clicked by the user.
In the previous tutorial example, when users click the one of the option buttons like Ok, Yes, No or Cancel on confirmation
dialog boxes, the showConfirmDialog() method will actually returns an integer code representing the clicked button.
Valid type codes are predefined as constants in the JOptionPane class:
JOptionPane.OK_OPTION - User clicked the Ok button.
JOptionPane.YES_OPTION - User clicked the Yes button.
JOptionPane.NO_OPTION - User clicked the No button.
JOptionPane.CANCEL_OPTION - User clicked the Cancel button.
JOptionPane.CLOSED_OPTION - User closed the confirmation dialog box.
Here is an example program I wrote to test the returned integer code of showConfirmDialog():
/**
* JOptionPaneConfirmDialogInput.java
* Copyright (c) 2009 by Dr. Herong Yang, http://www.herongyang.com/
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class JOptionPaneConfirmDialogInput implements ActionListener {
JFrame myFrame = null;
public static void main(String[] a) {
(new JOptionPaneConfirmDialogInput()).test();
}
private void test() {
myFrame = new JFrame("showConfirmDialog() Input Test");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container myPane = myFrame.getContentPane();
JButton myButton = new JButton("Show");
myButton.addActionListener(this);
myPane.add(myButton);
myFrame.pack();
myFrame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
int messageType = JOptionPane.INFORMATION_MESSAGE;
int optionType = JOptionPane.YES_NO_CANCEL_OPTION;
int code = JOptionPane.showConfirmDialog(myFrame,
"Do you want to continue?",
"Confirmation Dialog Box", optionType, messageType);
String answer = "Unknown";
if (code == JOptionPane.OK_OPTION) {
answer = "Ok";
} else if (code == JOptionPane.YES_OPTION) {
answer = "Yes";
} else if (code == JOptionPane.NO_OPTION) {
answer = "No";
} else if (code == JOptionPane.CANCEL_OPTION) {
answer = "Cancel";
} else if (code == JOptionPane.CLOSED_OPTION) {
answer = "Closed";
}
System.out.println("Answer: "+answer);
}
}
If you run this example, and click the Show button,
you will see a confirmation dialog box showing up like this:
Click the Yes button on the confirmation dialog box.
Click the Show button on the main frame window, then the No button on the confirmation dialog box again.
Repeat the test with the Cancel button and the close dialog box icon.
You will see some messages printed on the Java console window:
Answer: Ok
Answer: No
Answer: Cancel
Answer: Closed
Interesting notes about this tutorial example:
The returned code of the Yes button is JOptionPane.OK_OPTION, not JOptionPane.YES_OPTION. I don't know why.
Sample programs listed in this section have been tested with JDK 1.6.0.