Java Tutorial/Swing/JOptionPane Dialog — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 15:32, 31 мая 2010
Содержание
- 1 About dialog
- 2 Adding Components to the Button Area: Using JOptionPane with a JButton containing a text label and an icon
- 3 Big value list for JOptionInput Dialog
- 4 Complex message arguments
- 5 Confirm Pop-Ups
- 6 Create a Confirm Dialog Box
- 7 Create a Message Dialog Box
- 8 Creating a JOptionPane
- 9 Customize JOptionPane buttons
- 10 Customizing a JOptionPane Look and Feel
- 11 Dialog with default options
- 12 Dialog without parent component
- 13 Displaying Multiline Messages
- 14 Display JOptionPane
- 15 Input Pop-Ups
- 16 Instant Input Dialogs
- 17 JOptionPane Option Position Constants
- 18 JOptionPane Utility Class: Get selection from JOptionPane
- 19 JOptionPane WARNING_MESSAGE
- 20 Localize a JOptionPane dialog
- 21 Message Pop-Ups
- 22 Modal dialog with OK/cancel and a text field
- 23 Modal dialog with yes/no button
- 24 Modifiable JOptionPane
- 25 OK cancel option dialog
- 26 Option Pop-Ups
- 27 Sample JOptionPane in a JDialog
- 28 Setting JOptionPane button labels to French
- 29 String Array Option Popups
- 30 The JOptionPane Message Argument is an Object, not a String.
- 31 The JOptionPane Message Type and Icon Arguments
- 32 The JOptionPane Options and Initial Value Arguments
- 33 The JOptionPane Option Type Argument
- 34 Tip Of Day Dialog
- 35 To displays a dialog with a list of choices in a drop-down list box
- 36 Understanding the Message Property
- 37 Using JOptionPane to Display a Message
- 38 Using JOptionPane to Obtain User Input
- 39 Using JOptionPane to Prompt User Confirmation
- 40 Using JOptionPane to prompt user confirmation: a demo
- 41 Using JOptionPane with a JSlider
- 42 Using JOptionPane with a predefined selections
- 43 Wait for a click and then quit
- 44 Yes no cancel dialog
About dialog
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);
}
}
Adding Components to the Button Area: Using JOptionPane with a JButton containing a text label and an icon
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;
}
}
Big value list for JOptionInput Dialog
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");
}
}
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,
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);
}
}
Confirm Pop-Ups
- 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
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);
}
}
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.");
}
}
Creating a JOptionPane
A JOptionPane object represents a dialog box for several purposes:
- Display a message (through the use of the showMessageDialog method)
- Ask for user"s confirmation (using the showConfirmDialog method)
- Obtain the user"s input (using the showInputDialog method)
- Do the combined three above (using the showOptionDialog method)
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);
The panel presents content in four areas. All the areas are optional
- 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.
- Message Area: Display a text message.
- Input Area: Allow users to provide a response to a message.
- Button Area: For getting user input. Selection of a button signals the end of the usage of the JOptionPane.
Property Constants:
- ICON_PROPERTY
- INITIAL_SELECTION_VALUE_PROPERTY
- INITIAL_VALUE_PROPERTY
- INPUT_VALUE_PROPERTY
- MESSAGE_PROPERTY
- MESSAGE_TYPE_PROPERTY
- OPTION_TYPE_PROPERTY
- OPTIONS_PROPERTY
- SELECTION_VALUES_PROPERTY
- VALUE_PROPERTY
- WANTS_INPUT_PROPERTY
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);
}
}
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
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;
}
}
Dialog without parent component
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);
}
}
Displaying Multiline Messages
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<br>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;
}
}
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:
public JDialog createDialog(Component parentComponent, String title)
public JInternalFrame createInternalFrame(Component parentComponent, String title)
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).
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);
}
}
Instant Input Dialogs
import javax.swing.JOptionPane;
public class InstantInputDialog {
public static void main(String[] a) {
String input = JOptionPane.showInputDialog("Enter Input:");
System.out.println(input);
}
}
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
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();
}
}
JOptionPane Utility Class: Get selection from JOptionPane
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;
}
}
JOptionPane WARNING_MESSAGE
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);
}
}
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 Pop-Ups
With a message pop-up, there"s no return value.
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");
}
}
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;
}
}
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.
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]);
}
}
Sample JOptionPane in a JDialog
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);
}
}
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.
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);
}
}
String Array Option Popups
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]);
}
}
The JOptionPane Message Argument is an Object, not a String.
- If the message is an array of objects (Object[ ]), make the JOptionPane place each entry onto a separate row.
- If the message is a Component, place the component in the message area.
- If the message is an Icon, place the Icon within a JLabel and display the label in the message area.
- 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.
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();
}
}
The JOptionPane Message Type and Icon Arguments
- ERROR_MESSAGE for displaying an error message
- INFORMATION_MESSAGE for displaying an informational message
- QUESTION_MESSAGE for displaying a query message
- WARNING_MESSAGE for displaying a warning message
- PLAIN_MESSAGE for displaying any other type of message
The JOptionPane Options and Initial Value Arguments
- a Component, place the component in the button area.
- an Icon, place the Icon within a JButton and place the button in the button area.
- 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.
- DEFAULT_OPTION for a single OK button
- OK_CANCEL_OPTION for OK and Cancel buttons
- YES_NO_CANCEL_OPTION for Yes, No, and Cancel buttons
- YES_NO_OPTION for Yes and No buttons
Tip Of Day Dialog
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><b>Content</b></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);
}
}
To displays a dialog with a list of choices in a drop-down list box
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);
}
}
Understanding the Message Property
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);
}
}
Using JOptionPane to Display a Message
You use the JOptionPane class"s showMessageDialog method to display a message.
There are three overloads of this method.
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.
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)
The messageType argument specifies the type of the message, and its values is one of the following:
- JOptionPane.INFORMATION_MESSAGE
- JOptionPane.ERROR_MESSAGE
- JOptionPane.WARNING_MESSAGE
- JOptionPane.QUESTION_MESSAGE
- 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
- Using the showConfirmDialog static method to ask for user confirmation.
- This method displays a dialog with buttons on it, such as a Yes button, a No button, a Cancel button, or an OK button.
- You can select which buttons to appear or you can create your own buttons.
- Upon the user clicking a button, JOptionPane returns one of the following predefined ints:
- JOptionPane.YES_OPTION
- JOptionPane.NO_OPTION
- JOptionPane.CANCEL_OPTION
- 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.
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)
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
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");
}
}
}
Using JOptionPane with a JSlider
If the user doesn"t move the slider, JOptionPane.getInputValue() correctly returns JOptionPane.UNINITIALIZED_VALUE.
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;
}
}
Using JOptionPane with a predefined selections
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);
}
}
Wait for a 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;
}
}