JoptionPane showmessagedialog example

JOptionPane is used to prompt up a dialog to accept user input or informs a message, four types of dialog are supported: Message dialog, Confirmation dialog, Input dialog, and Options dialog.

Today we get learn how to use JoptionPane showmessagedialog – tutorial and example.

3 static methods are defined in class JOptionPane you can directly call neither one to create a dialog and display a message in dialog:

  • public static void showMessageDialog(Component parentComponent,
    Object message) throws HeadlessException;
  • public static void showMessageDialog(Component parentComponent,
    Object message, String title, int messageType) throws HeadlessException
  • public static void showMessageDialog(Component parentComponent,
    Object message, String title, int messageType, Icon icon) throws HeadlessException

They have a common parameter parentComponent, it defines the Component that is to be the parent of this dialog box. messageType defines the style of the message and possible value are listed below:

/** Used for error messages. */
public static final int  ERROR_MESSAGE = 0;
/** Used for information messages. */
public static final int  INFORMATION_MESSAGE = 1;
/** Used for warning messages. */
public static final int  WARNING_MESSAGE = 2;
/** Used for questions. */
public static final int  QUESTION_MESSAGE = 3;
/** No icon is used. */
public static final int   PLAIN_MESSAGE = -1;

joptionpane showmessagedialog example source code:

 public static void main(String[] args) {
        String[] choices = {"Value One", "Value Two", "None of your business", "Quit"};
        int response = JOptionPane.showOptionDialog(
                null                       // Center in window.
                , "How did you vote?"        // Message
                , "Party Poll"               // Title in titlebar
                , JOptionPane.YES_NO_OPTION  // Option type
                , JOptionPane.PLAIN_MESSAGE  // messageType
                , null                       // Icon (none)
                , choices                    // Button text as above.
                , "None of your business"    // Default button's label
        );

        //The first usage for joptionpane showmessagedialog example
        JOptionPane.showMessageDialog(null, "You choose " + choices[response]);
        //The second usage for joptionpane showmessagedialog example
        JOptionPane.showMessageDialog(null, "You choose " + choices[response], "JavaRMI.com", JOptionPane.INFORMATION_MESSAGE);
        //The third usage for joptionpane showmessagedialog example
        Icon icon = new ImageIcon("images/myImage.gif");
        JOptionPane.showMessageDialog(null, "You choose " + choices[response], "JavaRMI.com", JOptionPane.INFORMATION_MESSAGE, icon);

    }

Оцените статью
ASJAVA.COM
Добавить комментарий

Your email address will not be published. Required fields are marked *

*

code