Java Tutorial/Swing/JOptionPane Dialog

Материал из Java эксперт
Перейти к: навигация, поиск

Содержание

About dialog

   <source lang="java">

import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; class AboutDialog extends JDialog {

 public AboutDialog() {
   setTitle("About");
   setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
   add(Box.createRigidArea(new Dimension(0, 10)));
   JLabel name = new JLabel("Notes");
   name.setAlignmentX(0.5f);
   add(name);
   add(Box.createRigidArea(new Dimension(0, 100)));
   JButton close = new JButton("Close");
   close.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent event) {
       dispose();
     }
   });
   close.setAlignmentX(0.5f);
   add(close);
   setModalityType(ModalityType.APPLICATION_MODAL);
   setDefaultCloseOperation(DISPOSE_ON_CLOSE);
   setSize(300, 200);
 }

} public class SimpleDialog {

 public static void main(String[] args) {
   JMenuBar menubar = new JMenuBar();
   JMenu file = new JMenu("File");
   file.setMnemonic(KeyEvent.VK_F);
   JMenu help = new JMenu("Help");
   help.setMnemonic(KeyEvent.VK_H);
   JMenuItem about = new JMenuItem("About");
   help.add(about);
   about.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent event) {
       AboutDialog ad = new AboutDialog();
       ad.setVisible(true);
     }
   });
   menubar.add(file);
   menubar.add(help);
   JFrame f = new JFrame();
   f.setJMenuBar(menubar);
   f.setSize(300, 200);
   f.setLocationRelativeTo(null);
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   f.setVisible(true);
 }

}</source>





Adding Components to the Button Area: Using JOptionPane with a JButton containing a text label and an icon

   <source lang="java">

import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JOptionPane; public class AddingButtonWithActionListener {

 public static void main(String[] a) {
   JFrame frame = new JFrame();
   JOptionPane optionPane = new JOptionPane();
   optionPane.setMessage("I got an icon and a text label");
   optionPane.setMessageType(JOptionPane.INFORMATION_MESSAGE);
   Icon icon = new ImageIcon("yourFile.gif");
   JButton jButton = getButton(optionPane, "OK", icon);
   optionPane.setOptions(new Object[] { jButton });
   JDialog dialog = optionPane.createDialog(frame, "Icon/Text Button");
   dialog.setVisible(true);
 }
 public static JButton getButton(final JOptionPane optionPane, String text, Icon icon) {
   final JButton button = new JButton(text, icon);
   ActionListener actionListener = new ActionListener() {
     public void actionPerformed(ActionEvent actionEvent) {
       // Return current text label, instead of argument to method
       optionPane.setValue(button.getText());
       System.out.println(button.getText());
     }
   };
   button.addActionListener(actionListener);
   return button;
 }

}</source>





Big value list for JOptionInput Dialog

   <source lang="java">

import javax.swing.JFrame; import javax.swing.JOptionPane; public class BigValueJOptionpaneDialog {

 public static void main(String[] a) {
   JFrame frame = new JFrame();
   String bigList[] = new String[30];
   for (int i = 0; i < bigList.length; i++) {
     bigList[i] = Integer.toString(i);
   }
   JOptionPane.showInputDialog(frame, "Pick a printer", "Input", JOptionPane.QUESTION_MESSAGE,
       null, bigList, "Titan");
 }

}</source>





Complex message arguments

The message argument not only supports displaying an array of strings, but it also can support an array of any type of object. If the element is an Icon, the icon is placed within a JLabel,



   <source lang="java">

import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JOptionPane; import javax.swing.JSlider; public class ComplexMessageDemo {

 public static void main(String[] a) {
   Object complexMsg[] = { "Above Message", new ImageIcon("yourFile.gif"), new JButton("Hello"),
       new JSlider(), new ImageIcon("yourFile.gif"), "Below Message" };
   JOptionPane optionPane = new JOptionPane();
   optionPane.setMessage(complexMsg);
   optionPane.setMessageType(JOptionPane.INFORMATION_MESSAGE);
   JDialog dialog = optionPane.createDialog(null, "Width 100");
   dialog.setVisible(true);
 }

}</source>





Confirm Pop-Ups

  1. the return value signifies which button the user picked. The returned value is one of the integer constants: YES_OPTION, NO_OPTION, or CANCEL_OPTION



   <source lang="java">

import javax.swing.JFrame; import javax.swing.JOptionPane; public class ConfirmPopUps {

 public static void main(String[] a) {
   JFrame frame = new JFrame();
   int result = JOptionPane.showConfirmDialog(frame, "Continue printing?");
   // JOptionPane.showInternalConfirmDialog(desktop, "Continue printing?");
   System.out.println(JOptionPane.CANCEL_OPTION == result);
 }

}</source>





Create a Confirm Dialog Box

   <source lang="java">

import javax.swing.JOptionPane; public class Main {

 public static void main(String[] argv) throws Exception {
   int response = JOptionPane.showConfirmDialog(null, "Should i delete all files?");
 }

}</source>





Create a Message Dialog Box

   <source lang="java">

import javax.swing.JOptionPane; public class Main {

 public static void main(String[] argv) throws Exception {
   JOptionPane.showMessageDialog(null, "I am happy.");
 }

}</source>





Creating a JOptionPane

A JOptionPane object represents a dialog box for several purposes:

  1. Display a message (through the use of the showMessageDialog method)
  2. Ask for user"s confirmation (using the showConfirmDialog method)
  3. Obtain the user"s input (using the showInputDialog method)
  4. Do the combined three above (using the showOptionDialog method)



   <source lang="java">

public JOptionPane() JOptionPane optionPane = new JOptionPane(); public JOptionPane(Object message) JOptionPane optionPane = new JOptionPane("Message"); public JOptionPane(Object message, int messageType) JOptionPane optionPane = new JOptionPane("Message", JOptionPane.WARNING_MESSAGE); public JOptionPane(Object message, int messageType, int optionType) JOptionPane optionPane = new JOptionPane("Question?", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION); public JOptionPane(Object message, int messageType, int optionType, Icon icon) Icon printerIcon = new ImageIcon("yourFile.gif"); JOptionPane optionPane = new JOptionPane("Question?", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION, printerIcon); public JOptionPane(Object message, int messageType, int optionType, Icon icon, Object options[ ]) Icon greenIcon = new DiamondIcon(Color.GREEN); Icon redIcon = new DiamondIcon(Color.RED); Object optionArray[] = new Object[] { greenIcon, redIcon} ; JOptionPane optionPane = new JOptionPane("Question?", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION, printerIcon, optionArray); public JOptionPane(Object message, int messageType, int optionType, Icon icon, Object options[], Object initialValue) JOptionPane optionPane = new JOptionPane("Question?", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION, printerIcon, optionArray, redIcon);</source>



The panel presents content in four areas. All the areas are optional

  1. Icon Area: Display an Icon to indicate the type of message. The installed look and feel provides default icons for certain types of messages. You can provide your own icon.
  2. Message Area: Display a text message.
  3. Input Area: Allow users to provide a response to a message.
  4. Button Area: For getting user input. Selection of a button signals the end of the usage of the JOptionPane.

Property Constants:

  1. ICON_PROPERTY
  2. INITIAL_SELECTION_VALUE_PROPERTY
  3. INITIAL_VALUE_PROPERTY
  4. INPUT_VALUE_PROPERTY
  5. MESSAGE_PROPERTY
  6. MESSAGE_TYPE_PROPERTY
  7. OPTION_TYPE_PROPERTY
  8. OPTIONS_PROPERTY
  9. SELECTION_VALUES_PROPERTY
  10. VALUE_PROPERTY
  11. WANTS_INPUT_PROPERTY


Customize JOptionPane buttons

   <source lang="java">

import javax.swing.JOptionPane; public class Main {

 public static void main(String[] argv) throws Exception {
   String[] buttons = { "Yes", "Yes to all", "No", "Cancel" };
   int rc = JOptionPane.showOptionDialog(null, "Question ?", "Confirmation",
       JOptionPane.WARNING_MESSAGE, 0, null, buttons, buttons[2]);
   System.out.println(rc);
 }

}</source>





Customizing a JOptionPane Look and Feel

Property StringObject TypeOptionPane.actionMapActionMapOptionPane.backgroundColorOptionPane.borderBorderOptionPane.buttonAreaBorderBorderOptionPane.buttonClickThreshholdIntegerOptionPane.buttonFontFontOptionPane.buttonOrientationIntegerOptionPane.buttonPaddingIntegerOptionPane.cancelButtonMnemonicStringOptionPane.cancelButtonTextStringOptionPane.cancelIconIconOptionPane.errorDialog.border.backgroundColorOptionPane.errorDialog.titlePane.backgroundColorOptionPane.errorDialog.titlePane.foregroundColorOptionPane.errorDialog.titlePane.shadowColorOptionPane.errorIconIconOptionPane.errorSoundStringOptionPane.fontFontOptionPane.foregroundColorOptionPane.informationIconIconOptionPane.informationSoundStringOptionPane.inputDialogTitleStringOptionPane.isYesLastBooleanOptionPane.messageAnchorIntegerOptionPane.messageAreaBorderBorderOptionPane.messageFontFontOptionPane.messageForegroundColorOptionPane.messageDialogTitleStringOptionPane.minimumSizeDimensionOptionPane.noButtonMnemonicStringOptionPane.noButtonTextStringOptionPane.noIconIconOptionPane.okButtonMnemonicStringOptionPane.okButtonTextStringOptionPane.okIconIconOptionPane.questionDialog.border.backgroundColorOptionPane.questionDialog.titlePane.backgroundColorOptionPane.questionDialog.titlePane.foregroundColorOptionPane.questionDialog.titlePane.shadowColorOptionPane.questionIconIconOptionPane.questionSoundStringOptionPane.sameSizeButtonsBooleanOptionPane.separatorPaddingIntegerOptionPane.setButtonMarginBooleanOptionPane.titleTextStringOptionPane.warningDialog.border.backgroundColorOptionPane.warningDialog.titlePane.backgroundColorOptionPane.warningDialog.titlePane.foregroundColorOptionPane.warningDialog.titlePane.shadowColorOptionPane.warningIconIconOptionPane.warningSoundStringOptionPane.windowBindingsObject[ ]OptionPane.yesButtonMnemonicStringOptionPane.yesButtonTextStringOptionPane.yesIconIconOptionPaneUIString


Dialog with default options

   <source lang="java">

import java.awt.ruponent; import javax.swing.JOptionPane; public class Main {

 public static void main(String[] argv) throws Exception {
   int i = ok("Done.");
   System.out.println("ret : " + i);
 }
 public static int ok(String theMessage) {
   int result = JOptionPane.showConfirmDialog((Component) null, theMessage,
       "alert", JOptionPane.DEFAULT_OPTION);
   return result;
 }

}</source>





Dialog without parent component

   <source lang="java">

import javax.swing.JOptionPane; public class InputDialogWithPredefinedMessageIcon {

 public static void main(String[] a) {
   String input = JOptionPane.showInputDialog(null, "Enter Input:", "Dialog for Input",
       JOptionPane.WARNING_MESSAGE);
   System.out.println(input);
 }

}</source>





Displaying Multiline Messages

   <source lang="java">

import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JDialog; import javax.swing.JOptionPane; public class DisplayingMultilineMessages {

 public static void main(String[] a) {
   String msg = "<html>this is a really long message
this is a really long message this is a really long message this is a really long message this is a really long message this is a really long message this is a really long message"; JOptionPane optionPane = new NarrowOptionPane(); optionPane.setMessage(msg); optionPane.setMessageType(JOptionPane.INFORMATION_MESSAGE); JDialog dialog = optionPane.createDialog(null, "Width 100"); dialog.setVisible(true); }

} class NarrowOptionPane extends JOptionPane {

 NarrowOptionPane() {
 }
 public int getMaxCharactersPerLineCount() {
   return 100;
 }

}</source>





Display JOptionPane

JOptionPane includes two helper methods to place a JOptionPane within either a modal JDialog or a JInternalFrame and take care of all the previously described behavior:



   <source lang="java">

public JDialog createDialog(Component parentComponent, String title)

   public JInternalFrame createInternalFrame(Component parentComponent, String title)</source>
   
  
 
  



Input Pop-Ups

The return value is either what the user typed in a text field (a String) or what the user picked from a list of options (an Object).



   <source lang="java">

import javax.swing.JFrame; import javax.swing.JOptionPane; public class InputPopUps {

 public static void main(String[] a) {
   JFrame frame = new JFrame();
   Object result = JOptionPane.showInputDialog(frame, "Enter printer name:");
   System.out.println(result);
 }

}</source>





Instant Input Dialogs

   <source lang="java">

import javax.swing.JOptionPane; public class InstantInputDialog {

 public static void main(String[] a) {
   String input = JOptionPane.showInputDialog("Enter Input:");
   System.out.println(input);
 }

}</source>





JOptionPane Option Position Constants

PositionDescriptionCANCEL_OPTIONUsed when the Cancel button is pressedCLOSED_OPTIONUsed when the pop-up window closed without the user pressing a buttonNO_OPTIONUsed when the No button is pressedOK_OPTIONUsed when the OK button is pressedYES_OPTIONUsed when the Yes button is pressed



   <source lang="java">

import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; public class Test extends JFrame {

 public Test() {
   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   getContentPane().add(new JLabel("Placeholder label"));
   pack();
   setSize(200, 200);
   setVisible(true);
   int replaced = JOptionPane.showConfirmDialog(this,
       "Replace existing selection?");
   String result = "?";
   switch (replaced) {
   case JOptionPane.CANCEL_OPTION:
     result = "Canceled";
     break;
   case JOptionPane.CLOSED_OPTION:
     result = "Closed";
     break;
   case JOptionPane.NO_OPTION:
     result = "No";
     break;
   case JOptionPane.YES_OPTION:
     result = "Yes";
     break;
   default:
     ;
   }
   System.out.println("Replace? " + result);
 }
 public static void main(String[] args) {
   new Test();
 }

}</source>





JOptionPane Utility Class: Get selection from JOptionPane

   <source lang="java">

import javax.swing.JDialog; import javax.swing.JOptionPane; public class GettingJOptionPaneSelectionDemo {

 public static void main(String[] a) {
   String multiLineMsg[] = { "Hello,", "World" };
   JOptionPane pane = new JOptionPane();
   pane.setMessage(multiLineMsg);
   JDialog d = pane.createDialog(null, "title");
   d.setVisible(true);
   int selection = getSelection(pane);
   switch (selection) {
   case JOptionPane.OK_OPTION:
     System.out.println("OK_OPTION");
     break;
   case JOptionPane.CANCEL_OPTION:
     System.out.println("CANCEL");
     break;
   default:
     System.out.println("Others");
   }
 }
 public static int getSelection(JOptionPane optionPane) {
   int returnValue = JOptionPane.CLOSED_OPTION;
   Object selectedValue = optionPane.getValue();
   if (selectedValue != null) {
     Object options[] = optionPane.getOptions();
     if (options == null) {
       if (selectedValue instanceof Integer) {
         returnValue = ((Integer) selectedValue).intValue();
       }
     } else {
       for (int i = 0, n = options.length; i < n; i++) {
         if (options[i].equals(selectedValue)) {
           returnValue = i;
           break; // out of for loop
         }
       }
     }
   }
   return returnValue;
 }

}</source>





JOptionPane WARNING_MESSAGE

   <source lang="java">

import javax.swing.JOptionPane; public class InputDialogWithoutParentWindow {

 public static void main(String[] a) {
   String input = JOptionPane.showInputDialog(null, "Enter Input:", "Dialog for Input",
       JOptionPane.WARNING_MESSAGE);
   System.out.println(input);
 }

}</source>





Localize a JOptionPane dialog

   <source lang="java">

[JOptionPane_en.properties] Yes=Yes No=No Cancel=Cancel SaveMsg=Do you want to save your data [JOptionPane_fr.properties] Yes=Oui No=Non Cancel=Annuler SaveMsg=Voulez-vous sauvegarder vos donnees</source>





Message Pop-Ups

With a message pop-up, there"s no return value.



   <source lang="java">

import javax.swing.JFrame; import javax.swing.JOptionPane; public class MessagePopUps {

 public static void main(String[] a) {
   JFrame parent = new JFrame();
   JOptionPane.showMessageDialog(parent, "Printing complete");

// JOptionPane.showInternalMessageDialog(parent, "Printing complete");

 }

}</source>





Modal dialog with OK/cancel and a text field

   <source lang="java">

import javax.swing.JFrame; import javax.swing.JOptionPane; public class Main {

 public static void main(String[] argv) throws Exception {
   JFrame frame = new JFrame();
   String message = "message";
   String text = JOptionPane.showInputDialog(frame, message);
   if (text == null) {
     // User clicked cancel
   }
 }

}</source>





Modal dialog with yes/no button

   <source lang="java">

import javax.swing.JFrame; import javax.swing.JOptionPane; public class Main {

 public static void main(String[] argv) throws Exception {
   JFrame frame = new JFrame();
   String message = "message";
   int answer = JOptionPane.showConfirmDialog(frame, message);
   if (answer == JOptionPane.YES_OPTION) {
     // User clicked YES.
   } else if (answer == JOptionPane.NO_OPTION) {
     // User clicked NO.
   }
 }

}</source>





Modifiable JOptionPane

   <source lang="java">

/*

* $Id: ModifiableJOptionPane.java,v 1.1.1.1 2005/04/07 18:36:21 pocho Exp $
*/

import java.awt.ruponent; import java.awt.HeadlessException; import javax.swing.Icon; import javax.swing.JDialog; import javax.swing.JInternalFrame; import javax.swing.JOptionPane;

/**

* {@link javax.swing.JOptionPane} that can be modified for creating resizable
* dialogs and so on. Default implementation of {@link javax.swing.JOptionPane}
* creates allways unresizable dialog.
* 
* @version $Name:  $ - $Revision: 1.1.1.1 $ - $Date: 2005/04/07 18:36:21 $
*/

public class ModifiableJOptionPane extends JOptionPane {

 private boolean resizable;
 public ModifiableJOptionPane() {
   super();
 }
 /**
  * @param message
  */
 public ModifiableJOptionPane(Object message) {
   super(message);
 }
 /**
  * @param message
  * @param messageType
  */
 public ModifiableJOptionPane(Object message, int messageType) {
   super(message, messageType);
 }
 /**
  * @param message
  * @param messageType
  * @param optionType
  */
 public ModifiableJOptionPane(Object message, int messageType, int optionType) {
   super(message, messageType, optionType);
 }
 /**
  * @param message
  * @param messageType
  * @param optionType
  * @param icon
  */
 public ModifiableJOptionPane(Object message, int messageType, int optionType,
                             Icon icon) {
   super(message, messageType, optionType, icon);
 }
 /**
  * @param message
  * @param messageType
  * @param optionType
  * @param icon
  * @param options
  */
 public ModifiableJOptionPane(Object message, int messageType, int optionType,
                             Icon icon, Object[] options) {
   super(message, messageType, optionType, icon, options);
 }
 /**
  * @param message
  * @param messageType
  * @param optionType
  * @param icon
  * @param options
  * @param initialValue
  */
 public ModifiableJOptionPane(Object message, int messageType, int optionType,
                             Icon icon, Object[] options, Object initialValue) {
   super(message, messageType, optionType, icon, options, initialValue);
 }
 
 /**
  * @see javax.swing.JOptionPane#createDialog(java.awt.ruponent, java.lang.String)
  */
 public JDialog createDialog(Component parentComponent, String title)
     throws HeadlessException {
   JDialog dialog = super.createDialog(parentComponent, title);
   dialog.setResizable(isResizable());
   return dialog;
 }
 
 
 /**
  * @see javax.swing.JOptionPane#createInternalFrame(java.awt.ruponent, java.lang.String)
  */
 public JInternalFrame createInternalFrame(Component parentComponent,
                                           String title) {
   JInternalFrame frame = super.createInternalFrame(parentComponent, title);
   frame.setResizable(isResizable());
   return frame;
 }
 
 public void setResizable(boolean b) {
   this.resizable = b;
 }
 
 public boolean isResizable() {
   return resizable;
 }

}</source>





OK cancel option dialog

   <source lang="java">

import java.awt.ruponent; import javax.swing.JOptionPane; public class Main {

 public static void main(String[] argv) throws Exception {
   int i = okcancel("Are your sure ?");
   System.out.println("ret : " + i);
 }
 public static int okcancel(String theMessage) {
   int result = JOptionPane.showConfirmDialog((Component) null, theMessage,
       "alert", JOptionPane.OK_CANCEL_OPTION);
   return result;
 }

}</source>





Option Pop-Ups

With the option pop-up, the return value is an int. If the button labels are manually specified with a non-null argument, the integer represents the selected button position.



   <source lang="java">

import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JOptionPane; public class AddingIconsToOptionPopups {

 public static void main(String[] a) {
   JFrame frame = new JFrame();
   Icon greenIcon = new ImageIcon("yourFile.gif");
   Icon redIcon = new ImageIcon("");
   Object iconArray[] = { greenIcon, redIcon };
   JOptionPane.showOptionDialog(frame, "Continue printing?", "Select an Option",
       JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, iconArray, iconArray[1]);
 }

}</source>





Sample JOptionPane in a JDialog

   <source lang="java">

import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JOptionPane;

public class CreateDialogFromOptionPane {

 public static void main(final String[] args) {
   JFrame parent = new JFrame();
   JOptionPane optionPane = new JOptionPane("Continue printing?", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);
   JDialog dialog = optionPane.createDialog(parent, "Manual Creation");
   dialog.setVisible(true);
 }

}</source>





Setting JOptionPane button labels to French

To start the Java runtime with a different language, just set the user.language property, as in java -Duser.language=FR ClassName. Then, whenever you create a JOptionPane, you would get the French labels for Yes, No, OK, and Cancel.



   <source lang="java">

import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.UIManager; public class ConfigOptionPaneLanguage {

 public static void main(final String[] args) {

//

   UIManager.put("OptionPane.cancelButtonText", "Annuler");
   UIManager.put("OptionPane.noButtonText", "Non");
   UIManager.put("OptionPane.okButtonText", "D"accord");
   UIManager.put("OptionPane.yesButtonText", "Oui");
   JFrame parent = new JFrame();
   
   String multiLineMsg[] = { "Hello,", "World"} ;
   JOptionPane.showMessageDialog(parent, multiLineMsg);
 }

}</source>





String Array Option Popups

   <source lang="java">

import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JOptionPane; public class StringArrayOptionPopups {

 public static void main(String[] a) {
   JFrame frame = new JFrame();
   Icon blueIcon = new ImageIcon("yourFile.gif");
   Object stringArray[] = { "Do It", "No Way" };
   JOptionPane.showOptionDialog(frame, "Continue printing?", "Select an Option",
       JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, blueIcon, stringArray,
       stringArray[0]);
 }

}</source>





The JOptionPane Message Argument is an Object, not a String.

  1. If the message is an array of objects (Object[ ]), make the JOptionPane place each entry onto a separate row.
  2. If the message is a Component, place the component in the message area.
  3. If the message is an Icon, place the Icon within a JLabel and display the label in the message area.
  4. If the message is an Object, convert it to a String with toString(), place the String in a JLabel, and display the label in the message area.



   <source lang="java">

import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; public class Test2 extends JFrame {

 public Test2() {
   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   getContentPane().add(new JLabel("Placeholder label"));
   pack();
   setSize(200, 200);
   setVisible(true);
   Object msg[] = { "Complex Message", new JButton("A component"),
       new Object[] { "  Nested", "  Array" }, "for JOptionPane" };
   Object type[] = { "Animal", "Vegetable", "Mineral" };
   int result = JOptionPane.showOptionDialog(this, msg, "Choose",
       JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, type,
       null);
   System.out.println("Result (index)= " + result + " (" + type[result] + ")");
 }
 public static void main(String[] args) {
   new Test2();
 }

}</source>





The JOptionPane Message Type and Icon Arguments

  1. ERROR_MESSAGE for displaying an error message
  2. INFORMATION_MESSAGE for displaying an informational message
  3. QUESTION_MESSAGE for displaying a query message
  4. WARNING_MESSAGE for displaying a warning message
  5. PLAIN_MESSAGE for displaying any other type of message


The JOptionPane Options and Initial Value Arguments

  1. a Component, place the component in the button area.
  2. an Icon, place the Icon within a JButton and place the button in the button area.
  3. an Object, convert it to a String and place the String in a JButton, and place the button in the button area.

To have no buttons on the option pane, pass an empty array as the options setting: new Object[] { }.

If you want to have both an icon and a text label on the button, you can manually create a JButton and place it in the array.


The JOptionPane Option Type Argument

The optionType constructor argument is used to determine the configuration for the set of buttons in the button area.

  1. DEFAULT_OPTION for a single OK button
  2. OK_CANCEL_OPTION for OK and Cancel buttons
  3. YES_NO_CANCEL_OPTION for Yes, No, and Cancel buttons
  4. YES_NO_OPTION for Yes and No buttons


Tip Of Day Dialog

   <source lang="java">

import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.event.KeyEvent; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTextPane; public class TipOfDay {

 public static void main(String[] args) {
   JDialog d = new JDialog((Frame)null,"Tip of the Day");
   JPanel basic = new JPanel();
   basic.setLayout(new BoxLayout(basic, BoxLayout.Y_AXIS));
   d.add(basic);
   JPanel topPanel = new JPanel(new BorderLayout(0, 0));
   topPanel.setMaximumSize(new Dimension(450, 0));
   JLabel hint = new JLabel("This is the tip");
   hint.setBorder(BorderFactory.createEmptyBorder(10, 25, 10, 10));
   topPanel.add(hint);
   JSeparator separator = new JSeparator();
   separator.setForeground(Color.gray);
   topPanel.add(separator, BorderLayout.SOUTH);
   basic.add(topPanel);
   JPanel textPanel = new JPanel(new BorderLayout());
   textPanel.setBorder(BorderFactory.createEmptyBorder(15, 25, 15, 25));
   JTextPane pane = new JTextPane();
   pane.setContentType("text/html");
   String text = "<paragraph>Content</paragraph>";
   pane.setText(text);
   pane.setEditable(false);
   textPanel.add(new JScrollPane(pane));
   basic.add(textPanel);
   JPanel boxPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 20, 0));
   JCheckBox box = new JCheckBox("Show Tips at startup");
   box.setMnemonic(KeyEvent.VK_S);
   boxPanel.add(box);
   basic.add(boxPanel);
   JPanel bottom = new JPanel(new FlowLayout(FlowLayout.RIGHT));
   JButton ntip = new JButton("Next Tip");
   ntip.setMnemonic(KeyEvent.VK_N);
   JButton close = new JButton("Close");
   close.setMnemonic(KeyEvent.VK_C);
   bottom.add(ntip);
   bottom.add(close);
   basic.add(bottom);
   bottom.setMaximumSize(new Dimension(450, 0));
   d.setSize(new Dimension(450, 350));
   d.setResizable(false);
   d.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
   d.setVisible(true);
 }

}</source>





To displays a dialog with a list of choices in a drop-down list box

   <source lang="java">

import javax.swing.JOptionPane; public class InputDialogWithDropdownListbox {

 public static void main(String[] a) {
   String[] choices = { "A", "B", "C", "D", "E", "F" };
   String input = (String) JOptionPane.showInputDialog(null, "Choose now...",
       "The Choice of a Lifetime", JOptionPane.QUESTION_MESSAGE, null, // Use
                                                                       // default
                                                                       // icon
       choices, // Array of choices
       choices[1]); // Initial choice
   System.out.println(input);
 }

}</source>





Understanding the Message Property

   <source lang="java">

import javax.swing.JFrame; import javax.swing.JOptionPane; public class MesageDialogWithStringArray {

 public static void main(final String[] args) {
   JFrame parent = new JFrame();
   String multiLineMsg[] = { "Hello,", "World"} ;
   JOptionPane.showMessageDialog(parent, multiLineMsg);
 }

}</source>





Using JOptionPane to Display a Message

   <source lang="java">

You use the JOptionPane class"s showMessageDialog method to display a message. There are three overloads of this method.</source>





Using JOptionPane to Obtain User Input

To obtain user input, using the showInputDialog method. The showInputDialog method has six overloads whose signatures are as follows.



   <source lang="java">

public static java.lang.String showInputDialog (java.awt.ruponent parent, java.lang.Object message) public static java.lang.String showInputDialog (java.awt.ruponent parent, java.lang.Object message, java.lang.Object initialSelectionValue) public static java.lang.String showInputDialog (java.awt.ruponent parent, java.lang.Object message, java.lang.String title, int messageType) public static java.lang.String showInputDialog (java.awt.ruponent parent, java.lang.Object message, java.lang.String title, int messageType, Icon icon, java.lang.Object[] selectionValues, java.lang.Object initialSelectionValue) public static java.lang.String showInputDialog (java.lang.Object message) public static java.lang.Object showInputDialog (java.lang.Object message, java.lang.Object intialSelectionValue)</source>



The messageType argument specifies the type of the message, and its values is one of the following:

  1. JOptionPane.INFORMATION_MESSAGE
  2. JOptionPane.ERROR_MESSAGE
  3. JOptionPane.WARNING_MESSAGE
  4. JOptionPane.QUESTION_MESSAGE
  5. JOptionPane.PLAIN_MESSAGE

The selectionValues argument specifies an array of objects that provides possible selections. The initialSelectionValue argument specifies the initial value in the input field.


Using JOptionPane to Prompt User Confirmation

  1. Using the showConfirmDialog static method to ask for user confirmation.
  2. This method displays a dialog with buttons on it, such as a Yes button, a No button, a Cancel button, or an OK button.
  3. You can select which buttons to appear or you can create your own buttons.
  4. Upon the user clicking a button, JOptionPane returns one of the following predefined ints:
  1. JOptionPane.YES_OPTION
  2. JOptionPane.NO_OPTION
  3. JOptionPane.CANCEL_OPTION
  4. JOptionPane.OK_OPTION

If the user closes a JOptionPane by clicking the close button at the top right hand corner of the dialog, the JOptionPane.CLOSED_OPTION int is returned. The showConfirmDialog method has four overloads whose signatures are as follows.



   <source lang="java">

public static int showConfirmDialog (java.awt.ruponent parent, java.lang.Object message) public static int showConfirmDialog (java.awt.ruponent parent, java.lang.Object message, java.lang.String title, int optionType) public static int showConfirmDialog (java.awt.ruponent parent, java.lang.Object message, java.lang.String title, int optionType, int messageType) public static int showConfirmDialog (java.awt.ruponent parent, java.lang.Object message, java.lang.String title, int optionType, int messageType, Icon icon)</source>



If the first overload is used where there is no argument optionType is required, JOptionPane.YES_NO_CANCEL_OPTION is assumed.


Using JOptionPane to prompt user confirmation: a demo

   <source lang="java">

import javax.swing.JOptionPane; import javax.swing.JDialog; import javax.swing.JOptionPane; public class JOptionPaneTest2 {

 public static void main(String[] args) {
   JDialog.setDefaultLookAndFeelDecorated(true);
   int response = JOptionPane.showConfirmDialog(null, "Do you want to continue?", "Confirm",
       JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
   if (response == JOptionPane.NO_OPTION) {
     System.out.println("No button clicked");
   } else if (response == JOptionPane.YES_OPTION) {
     System.out.println("Yes button clicked");
   } else if (response == JOptionPane.CLOSED_OPTION) {
     System.out.println("JOptionPane closed");
   }
 }

}</source>





Using JOptionPane with a JSlider

If the user doesn"t move the slider, JOptionPane.getInputValue() correctly returns JOptionPane.UNINITIALIZED_VALUE.



   <source lang="java">

import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JSlider; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class JSliderOnJOptionPane {

 public static void main(final String[] args) {
   JFrame parent = new JFrame();
   JOptionPane optionPane = new JOptionPane();
   JSlider slider = getSlider(optionPane);
   optionPane.setMessage(new Object[] { "Select a value: ", slider });
   optionPane.setMessageType(JOptionPane.QUESTION_MESSAGE);
   optionPane.setOptionType(JOptionPane.OK_CANCEL_OPTION);
   JDialog dialog = optionPane.createDialog(parent, "My Slider");
   dialog.setVisible(true);
   System.out.println("Input: " + optionPane.getInputValue());
 }
 static JSlider getSlider(final JOptionPane optionPane) {
   JSlider slider = new JSlider();
   slider.setMajorTickSpacing(10);
   slider.setPaintTicks(true);
   slider.setPaintLabels(true);
   ChangeListener changeListener = new ChangeListener() {
     public void stateChanged(ChangeEvent changeEvent) {
       JSlider theSlider = (JSlider) changeEvent.getSource();
       if (!theSlider.getValueIsAdjusting()) {
         optionPane.setInputValue(new Integer(theSlider.getValue()));
       }
     }
   };
   slider.addChangeListener(changeListener);
   return slider;
 }

}</source>





Using JOptionPane with a predefined selections

   <source lang="java">

import javax.swing.JDialog; import javax.swing.JOptionPane; public class JOptionPaneTest3 {

 public static void main(String[] args) {
   JDialog.setDefaultLookAndFeelDecorated(true);
   Object[] selectionValues = { "Pandas", "Dogs", "Horses" };
   String initialSelection = "Dogs";
   Object selection = JOptionPane.showInputDialog(null, "What are your favorite animals?",
       "Zoo Quiz", JOptionPane.QUESTION_MESSAGE, null, selectionValues, initialSelection);
   System.out.println(selection);
 }

}</source>





Wait for a click and then quit

   <source lang="java">

import javax.swing.JDialog; import javax.swing.JOptionPane; public class Main {

 public static void main(String[] argv) throws Exception {
   JOptionPane pane = new JOptionPane("your message",JOptionPane.ERROR_MESSAGE, JOptionPane.OK_OPTION);
   JDialog d = pane.createDialog(null, "title");
   d.pack();
   d.setModal(false);
   d.setVisible(true);
   while (pane.getValue() == JOptionPane.UNINITIALIZED_VALUE) {
     try {
       Thread.sleep(100);
     } catch (InterruptedException ie) {
     }
   }
   System.exit(0);
 }

}</source>





Yes no cancel dialog

   <source lang="java">

import java.awt.ruponent; import javax.swing.JOptionPane; public class Main {

 public static void main(String[] argv) throws Exception {
   int i = yesnocancel("Are your sure ?");
   System.out.println("ret : " + i);
 }
 public static int yesnocancel(String theMessage) {
   int result = JOptionPane.showConfirmDialog((Component) null, theMessage,"alert", JOptionPane.YES_NO_CANCEL_OPTION);
   return result;
 }

}</source>