4 Ways to Show JOptionPane Confirm Dialog

Screenshot of confirm dialog
The following example illustrates 4 ways to show confirm dialog in JOptionPane.

import javax.swing.*;
import java.awt.*;
class ConfirmDialogExample extends JFrame
{

    public ConfirmDialogExample()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("JSplitPane Example");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
       
        // These display one after the other is closed
        JOptionPane.showConfirmDialog(this,"This is message - 1");
        JOptionPane.showConfirmDialog(this,"This is message - 2 - with yes_no","This is title",JOptionPane.YES_NO_OPTION);
        JOptionPane.showConfirmDialog(this,"This is message - 3 - with message type and ok_cancel","This is title",JOptionPane.OK_CANCEL_OPTION,JOptionPane.WARNING_MESSAGE);
        JOptionPane.showConfirmDialog(this,"This is message - 4 - with icon","This is title",JOptionPane.OK_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE,new ImageIcon("imageicon.png"));
       
       
        setSize(400,400);
        setVisible(true);   
    }
   
    public static void main(String args[])
    {
    SwingUtilities.invokeLater(new Runnable(){
            public void run()
            {
            new ConfirmDialogExample();
            }
        });
    }
}

showConfirmDialog(): This method takes in several parameters. If you were able to understand the last one, you'll understand all the remaining. The first parameter is the parent component, next is the message to be displayed, followed by title of JOptionPane, the type of option, type of message and custom icon image.

By default, title will be Select an Option, option type will be YES_NO_CANCEL_OPTION, type of message will be QUESTION_MESSAGE


Posted by at on

Tags: Swing Components,