Java/Swing JFC/OptionPane — различия между версиями

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

Текущая версия на 06:41, 1 июня 2010

A Program that Uses the JOptionPane Class to Get User Input

   

import javax.swing.JOptionPane;
public class MainClass {
  public static void main(String[] args) {
    String s;
    s = JOptionPane.showInputDialog("Enter an integer:");
    int x = Integer.parseInt(s);
    System.out.println("You entered " + x + ".");
  }
}





Create a Confirm Dialog Box

  
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?");
  }
}





Create a Message Dialog Box

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





Create a message dialog box with different options

  
import java.awt.ruponent;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Main extends JFrame {
  public Main() throws HeadlessException {
    setSize(200, 200);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JButton button1 = new JButton("Message dialog");
    button1.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        JOptionPane.showMessageDialog((Component) e.getSource(), "Thank you!");
      }
    });
    JButton button2 = new JButton("Input dialog");
    button2.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        String text = JOptionPane.showInputDialog((Component) e.getSource(), "What is your name?");
        if (text != null && !text.equals("")) {
          JOptionPane.showMessageDialog((Component) e.getSource(), "Hello " + text);
        }
      }
    });
    JButton button3 = new JButton("Yes no dialog");
    button3.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        int result = JOptionPane.showConfirmDialog((Component) e.getSource(),
            "Close this application?");
        if (result == JOptionPane.YES_OPTION) {
          System.exit(0);
        } else if (result == JOptionPane.NO_OPTION) {
          System.out.println("Do nothing");
        }
      }
    });
    setLayout(new FlowLayout(FlowLayout.CENTER));
    getContentPane().add(button1);
    getContentPane().add(button2);
    getContentPane().add(button3);
  }
  public static void main(String[] args) {
    new Main().setVisible(true);
  }
}





Customize JOptionPane buttons

  
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);
  }
}





Demonstrate JOptionPane

  
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
/**
 * Demonstrate JOptionPane
 * 
 * @author Ian Darwin
 */
public class JOptionDemo extends JFrame {
  // Constructor
  JOptionDemo(String s) {
    super(s);
    Container cp = getContentPane();
    cp.setLayout(new FlowLayout());
    JButton b = new JButton("Give me a message");
    b.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        JOptionPane.showMessageDialog(JOptionDemo.this,
            "This is your message: etaoin shrdlu", "Coded Message",
            JOptionPane.INFORMATION_MESSAGE);
      }
    });
    cp.add(b);
    b = new JButton("Goodbye!");
    b.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.exit(0);
      }
    });
    cp.add(b);
    // size the main window
    pack();
  }
  public static void main(String[] arg) {
    JOptionDemo x = new JOptionDemo("Testing 1 2 3...");
    x.setVisible(true);
  }
}





Demonstrates JoptionPane

  
// : c14:MessageBoxes.java
// Demonstrates JoptionPane.
// <applet code=MessageBoxes width=200 height=150></applet>
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class MessageBoxes extends JApplet {
  private JButton[] b = { new JButton("Alert"), new JButton("Yes/No"),
      new JButton("Color"), new JButton("Input"), new JButton("3 Vals") };
  private JTextField txt = new JTextField(15);
  private ActionListener al = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
      String id = ((JButton) e.getSource()).getText();
      if (id.equals("Alert"))
        JOptionPane.showMessageDialog(null, "There"s a bug on you!",
            "Hey!", JOptionPane.ERROR_MESSAGE);
      else if (id.equals("Yes/No"))
        JOptionPane.showConfirmDialog(null, "or no", "choose yes",
            JOptionPane.YES_NO_OPTION);
      else if (id.equals("Color")) {
        Object[] options = { "Red", "Green" };
        int sel = JOptionPane.showOptionDialog(null, "Choose a Color!",
            "Warning", JOptionPane.DEFAULT_OPTION,
            JOptionPane.WARNING_MESSAGE, null, options, options[0]);
        if (sel != JOptionPane.CLOSED_OPTION)
          txt.setText("Color Selected: " + options[sel]);
      } else if (id.equals("Input")) {
        String val = JOptionPane
            .showInputDialog("How many fingers do you see?");
        txt.setText(val);
      } else if (id.equals("3 Vals")) {
        Object[] selections = { "First", "Second", "Third" };
        Object val = JOptionPane.showInputDialog(null, "Choose one",
            "Input", JOptionPane.INFORMATION_MESSAGE, null,
            selections, selections[0]);
        if (val != null)
          txt.setText(val.toString());
      }
    }
  };
  public void init() {
    Container cp = getContentPane();
    cp.setLayout(new FlowLayout());
    for (int i = 0; i < b.length; i++) {
      b[i].addActionListener(al);
      cp.add(b[i]);
    }
    cp.add(txt);
  }
  public static void main(String[] args) {
    run(new MessageBoxes(), 200, 200);
  }
  public static void run(JApplet applet, int width, int height) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(applet);
    frame.setSize(width, height);
    applet.init();
    applet.start();
    frame.setVisible(true);
  }
} ///:~





Dialog with default options

  
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;
  }
}





Display error message dialog with JOptionPane.ERROR_MESSAGE

  
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class JOptionPaneERROR_MESSAGE {
  public static void main(String[] args) {
    final JPanel panel = new JPanel();
    JOptionPane.showMessageDialog(panel, "Could not open file", "Error", JOptionPane.ERROR_MESSAGE);
  }
}





Display information message dialog with JOptionPane.INFORMATION_MESSAGE

  
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class JOptionPaneINFORMATION_MESSAGE {
  public static void main(String[] args) {
    final JPanel panel = new JPanel();
    JOptionPane.showMessageDialog(panel, "Download completed", "Question",
        JOptionPane.INFORMATION_MESSAGE);
  }
}





Display question message dialog with JOptionPane.QUESTION_MESSAGE

  
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class JOptionPaneQUESTION_MESSAGE {
  public static void main(String[] args) {
    final JPanel panel = new JPanel();

    JOptionPane.showMessageDialog(panel, "Are you sure to quit?", "Question",
        JOptionPane.QUESTION_MESSAGE);
  }
}





Display warning message dialog with JOptionPane.WARNING_MESSAGE

  

import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class JOptionPaneWARNING_MESSAGE {
  public static void main(String[] args) {
    final JPanel panel = new JPanel();
    JOptionPane.showMessageDialog(panel, "A deprecated call", "Warning",
        JOptionPane.WARNING_MESSAGE);
  }
}





Exercise Options

  
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setSize(200, 200);
    frame.setVisible(true);
    JOptionPane.showMessageDialog(frame, "A");
    JOptionPane.showMessageDialog(frame, "B", "message", JOptionPane.WARNING_MESSAGE);
    int result = JOptionPane.showConfirmDialog(null, "Remove now?");
    switch (result) {
    case JOptionPane.YES_OPTION:
      System.out.println("Yes");
      break;
    case JOptionPane.NO_OPTION:
      System.out.println("No");
      break;
    case JOptionPane.CANCEL_OPTION:
      System.out.println("Cancel");
      break;
    case JOptionPane.CLOSED_OPTION:
      System.out.println("Closed");
      break;
    }
    String name = JOptionPane.showInputDialog(null, "Please enter your name.");
    System.out.println(name);
    JTextField userField = new JTextField();
    JPasswordField passField = new JPasswordField();
    String message = "Please enter your user name and password.";
    result = JOptionPane.showOptionDialog(frame, new Object[] { message, userField, passField },
        "Login", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
    if (result == JOptionPane.OK_OPTION)
      System.out.println(userField.getText() + " " + new String(passField.getPassword()));
  }
}





JOptionPane demo

  
/*
Definitive Guide to Swing for Java 2, Second Edition
By John Zukowski     
ISBN: 1-893115-78-X
Publisher: APress
*/
import java.awt.BorderLayout;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.JButton;
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 ManualDisplayPopup {
  public static void main(String args[]) {
    JFrame frame = new JFrame("NoButton Popup");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JButton button = new JButton("Ask");
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        Component source = (Component) actionEvent.getSource();
        JOptionPane optionPane = new JOptionPane("Continue printing?",
            JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);
        JDialog dialog = optionPane.createDialog(source,
            "Manual Creation");
        dialog.show();
        int selection = OptionPaneUtils.getSelection(optionPane);
        System.out.println(selection);
      }
    };
    button.addActionListener(actionListener);
    Container contentPane = frame.getContentPane();
    contentPane.add(button, BorderLayout.SOUTH);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}
final class OptionPaneUtils {
  private OptionPaneUtils() {
  }
  public static JOptionPane getNarrowOptionPane(int maxCharactersPerLineCount) {
    // Our inner class definition
    class NarrowOptionPane extends JOptionPane {
      int maxCharactersPerLineCount;
      NarrowOptionPane(int maxCharactersPerLineCount) {
        this.maxCharactersPerLineCount = maxCharactersPerLineCount;
      }
      public int getMaxCharactersPerLineCount() {
        return maxCharactersPerLineCount;
      }
    }
    return new NarrowOptionPane(maxCharactersPerLineCount);
  }
  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());
      }
    };
    button.addActionListener(actionListener);
    return button;
  }
  public 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;
  }
  public static int getSelection(JOptionPane optionPane) {
    // Default return value, signals nothing selected
    int returnValue = JOptionPane.CLOSED_OPTION;
    // Get selected Value
    Object selectedValue = optionPane.getValue();
    System.out.println(selectedValue);
    // If none, then nothing selected
    if (selectedValue != null) {
      Object options[] = optionPane.getOptions();
      if (options == null) {
        // default buttons, no array specified
        if (selectedValue instanceof Integer) {
          returnValue = ((Integer) selectedValue).intValue();
        }
      } else {
        // Array of option buttons specified
        for (int i = 0, n = options.length; i < n; i++) {
          if (options[i].equals(selectedValue)) {
            returnValue = i;
            break; // out of for loop
          }
        }
      }
    }
    return returnValue;
  }
}





JOptionPane utilities

  
/*
Definitive Guide to Swing for Java 2, Second Edition
By John Zukowski     
ISBN: 1-893115-78-X
Publisher: APress
*/
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public final class OptionPaneUtils {
  private OptionPaneUtils() {
  }
  public static JOptionPane getNarrowOptionPane(int maxCharactersPerLineCount) {
    // Our inner class definition
    class NarrowOptionPane extends JOptionPane {
      int maxCharactersPerLineCount;
      NarrowOptionPane(int maxCharactersPerLineCount) {
        this.maxCharactersPerLineCount = maxCharactersPerLineCount;
      }
      public int getMaxCharactersPerLineCount() {
        return maxCharactersPerLineCount;
      }
    }
    return new NarrowOptionPane(maxCharactersPerLineCount);
  }
  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());
      }
    };
    button.addActionListener(actionListener);
    return button;
  }
  public 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;
  }
  public static int getSelection(JOptionPane optionPane) {
    // Default return value, signals nothing selected
    int returnValue = JOptionPane.CLOSED_OPTION;
    // Get selected Value
    Object selectedValue = optionPane.getValue();
    System.out.println(selectedValue);
    // If none, then nothing selected
    if (selectedValue != null) {
      Object options[] = optionPane.getOptions();
      if (options == null) {
        // default buttons, no array specified
        if (selectedValue instanceof Integer) {
          returnValue = ((Integer) selectedValue).intValue();
        }
      } else {
        // Array of option buttons specified
        for (int i = 0, n = options.length; i < n; i++) {
          if (options[i].equals(selectedValue)) {
            returnValue = i;
            break; // out of for loop
          }
        }
      }
    }
    return returnValue;
  }
}





Localize a JOptionPane dialog

  
[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





Message dialog helper

   

/*
 * Copyright (C) 2001-2003 Colin Bell
 * colbell@users.sourceforge.net
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
import java.awt.ruponent;
import java.awt.Frame;
import java.io.File;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
/**
 * This class provides some methods for using standard JDK dialogs.
 *
 * @author 
 */
public class Dialogs
{
  public static void showNotYetImplemented(Component owner)
  {
    JOptionPane.showMessageDialog(owner, "Not Yet Implemented","", JOptionPane.INFORMATION_MESSAGE);
  }
  public static boolean showYesNo(Component owner, String msg)
  {
    return showYesNo(owner, msg, "");
  }
  public static boolean showYesNo(Component owner, String msg, String title)
  {
    int rc = JOptionPane.showConfirmDialog(owner, msg, title,
                        JOptionPane.YES_NO_OPTION);
    return rc == JOptionPane.YES_OPTION;
  }
  public static void showOk(Component owner, String msg)
  {
    JOptionPane.showMessageDialog(owner, msg, "", JOptionPane.INFORMATION_MESSAGE);
  }
  private static boolean canSaveToFile(Frame parentFrame, File outFile)
  {
    if (!outFile.exists())
    {
      return true;
    }
    String msg = "Alreadyexists" + outFile.getAbsolutePath();
    if (!Dialogs.showYesNo(parentFrame, msg))
    {
      return false;
    }
    if (!outFile.canWrite())
    {
      msg = "Cannotwrite" + outFile.getAbsolutePath();
      Dialogs.showOk(parentFrame, msg);
      return false;
    }
    outFile.delete();
    return true;
  }
}





Modal dialog with OK/cancel and a text field

  
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
    }
  }
}





Modal dialog with yes/no button

  
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.
    }
  }
}





Modifiable JOptionPane

   
/*
 * $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;
  }
}





OK cancel option dialog

  
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;
  }
}





OptionPane Sample: simple dialog

  
import java.awt.BorderLayout;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class OptionPaneSample {
  public static void main(String args[]) {
    JFrame f = new JFrame("JOptionPane Sample");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container content = f.getContentPane();
    JButton button = new JButton("Ask");
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        Component source = (Component) actionEvent.getSource();
        Object response = JOptionPane.showInputDialog(source,
            "Where do you want to go tomorrow?",
            "JOptionPane Sample", JOptionPane.QUESTION_MESSAGE,
            null, new String[] { "A","B", "C","D","E" },"E");
        System.out.println("Response: " + response);
      }
    };
    button.addActionListener(actionListener);
    content.add(button, BorderLayout.CENTER);
    f.setSize(300, 200);
    f.setVisible(true);
  }
}





Show a message dialog with JOptionPane

  
import javax.swing.JOptionPane;
public class Main {
  public static void main(String[] argv) {
    JOptionPane.showMessageDialog(null, "The message", "The Title", JOptionPane.INFORMATION_MESSAGE);
  }
}





Show message in two lines in a dialog box

  
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Modal dialog with OK button
    String message = "Line1\nLine2";
    JFrame frame = new JFrame();
    JOptionPane.showMessageDialog(frame, message);
  }
}





Simple Input Dialog

  
import java.awt.BorderLayout;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class SamplePopup {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Sample Popup");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JButton button = new JButton("Ask");
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        Component source = (Component) actionEvent.getSource();
        Object response = JOptionPane.showInputDialog(source,
            "Where would you like to go to lunch?",
            "Select a Destination", JOptionPane.QUESTION_MESSAGE,
            null, new String[] { "A", "B","C", "D", "E" },"B");
        System.out.println("Response: " + response);
      }
    };
    button.addActionListener(actionListener);
    Container contentPane = frame.getContentPane();
    contentPane.add(button, BorderLayout.SOUTH);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}





Use a JOptionPane

  
import java.awt.ruponent;
import javax.swing.JOptionPane;
public class Main {
  public static int yesno(String theMessage) {
    int result = JOptionPane.showConfirmDialog((Component) null, theMessage,
        "alert", JOptionPane.YES_NO_OPTION);
    return result;
  }
  public static void main(String args[]) {
    int i = yesno("Are your sure ?");
    System.out.println("ret : " + i);
  }
}





Wait (forever) for a non-null click and then quit

  
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);
  }
}





Yes no cancel dialog

  
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;
  }
}