Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 

Swing Chapter 14. (The basics) Dialogs. Easy for reading, Click here!

Custom Search
Swing Chapter 14. (The basics) Dialogs. Easy for reading, Click here!

[ Return to Swing (Book) ]

Page: 3/5 



Previous Page Previous Page (2/5) - Next Page (4/5) Next Page
Subpages: 1. Dialogs and choosers overview 
2.
Adding an "About" dialog 
3.
JOptionPane message dialogs 
4. Customizing JColorChooser 
5. Customizing JFileChooser 

14.3  JOptionPane message dialogs

Message dialogs provided by the JOptionPane class can be used for many purposes in Swing apps: to post a message, ask a question, or get simple user input. The following example brings up several message boxes of different types with a common Shakespeare theme. Both internal and regular dialogs are constructed, demonstrating how to use the convenient showXXDialog() methods (see 14.1.2), as well as how to manually create a JOptionPane component and place it in a dialog or internal frame for display.

Each dialog is instantiated as needed and we perform no caching here (for purposes of demonstration). A more professional implementation might instantiate each dialog at startup and store them as variables for use throughout the application's lifetime.

Figure 14.6 JOptionPane with custom icon, message, and option button strings in a JDialog.

<<file figure14-6.gif>>

Figure 14.7 JOptionPane with custom icon and message in a JInternalFrame.

<<file figure14-7.gif>>

Figure 14.8 JOptionPane ERROR_MESSAGE message dialog with multi-line message.

<<file figure14-8.gif>>

Figure 14.9 JOptionPane INFORMATION_MESSAGE input dialog with custom icon, message, text field input, and initial selection.

<<file figure14-9.gif>>

Figure 14.10 JOptionPane INFORMATION_MESSAGE input dialog with custom icon, message, combo box input, and initial selection.

<<file figure14-10.gif>>

Figure 14.11 JOptionPane YES_NO_OPTION confirm dialog.

<<file figure14-11.gif>>

The Code: DialogBoxes.java

see \Chapter14\2

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class DialogBoxes extends JFrame

{

  static final String BOX_TITLE = "Shakespeare Boxes";

  public DialogBoxes() {

    super(BOX_TITLE);

    setSize(400,300);

    setLayeredPane(new JDesktopPane());

    JMenuBar menuBar = createMenuBar();

    setJMenuBar(menuBar);

    WindowListener wndCloser = new WindowAdapter() {

      public void windowClosing(WindowEvent e) {

        System.exit(0);

      }

    };

    addWindowListener(wndCloser);

    setVisible(true);

  }

  protected JMenuBar createMenuBar() {

    JMenuBar menuBar = new JMenuBar();

    JMenu mFile = new JMenu("File");

    mFile.setMnemonic('f');

    JMenuItem mItem = new JMenuItem("Ask Question");

    mItem.setMnemonic('q');

    ActionListener lst = new ActionListener() {

      public void actionPerformed(ActionEvent e) {

        JOptionPane pane = new JOptionPane(

          "To be or not to be ?\nThat is the question.");

        pane.setIcon(new ImageIcon("Hamlet.gif"));

        Object[] options =

          new String[] {"To be", "Not to be"};

        pane.setOptions(options);

        JDialog dialog = pane.createDialog(

        DialogBoxes.this, BOX_TITLE);

        dialog.show();

        Object obj = pane.getValue();

        int result = -1;

        for (int k=0; k<options.length; k++)

          if (options[k].equals(obj))

        result = k;

        System.out.println("User's choice: "+result);

      }

    };

    mItem.addActionListener(lst);

    mFile.add(mItem);

    mItem = new JMenuItem("nfo Message");

    mItem.setMnemonic('i');

    lst = new ActionListener() {

      public void actionPerformed(ActionEvent e) {

        String message = "William Shakespeare was born\n"+

          "on April 23, 1564 in\n"

          +"Stratford-on-Avon near London";

        JOptionPane pane = new JOptionPane(message);

        pane.setIcon(new ImageIcon("Shakespeare.gif"));

        JInternalFrame frame = pane.createInternalFrame(

          (DialogBoxes.this).getLayeredPane(), BOX_TITLE);

        getLayeredPane().add(frame);

      }

    };

    mItem.addActionListener(lst);

    mFile.add(mItem);

    mItem = new JMenuItem("Error Message");

    mItem.setMnemonic('e');

    lst = new ActionListener() {

      public void actionPerformed(ActionEvent e) {

        String message = "\"The Comedy of Errors\"\n"+

          "s considered by many scholars to be\n"+

          "the first play Shakespeare wrote";

        JOptionPane.showMessageDialog(

          DialogBoxes.this, message,

          BOX_TITLE, JOptionPane.ERROR_MESSAGE);

      }

    };

    mItem.addActionListener(lst);

    mFile.add(mItem);

    mFile.addSeparator();

    mItem = new JMenuItem("Text Input");

    mItem.setMnemonic('t');

    lst = new ActionListener() {

      public void actionPerformed(ActionEvent e) {

        String input = (String) JOptionPane.showInputDialog(

          DialogBoxes.this,

          "Please enter your favorite Shakespeare play",

          BOX_TITLE, JOptionPane.INFORMATION_MESSAGE,

          new ImageIcon("Plays.jpg"), null,

          "Romeo and Juliet");

        System.out.println("User's input: "+input);

      }

    };

    mItem.addActionListener(lst);

    mFile.add(mItem);

    mItem = new JMenuItem("Combobox Input");

    mItem.setMnemonic('c');

    lst = new ActionListener() {

      public void actionPerformed(ActionEvent e) {

        String[] plays = new String[] {

          "Hamlet", "King Lear", "Otello", "Romeo and Juliet" };

        String input = (String) JOptionPane.showInputDialog(

          DialogBoxes.this,

          "Please select your favorite Shakespeare play",

          BOX_TITLE, JOptionPane.INFORMATION_MESSAGE,

          new ImageIcon("Books.gif"), plays,

          "Romeo and Juliet");

        System.out.println("User's input: "+input);

      }

    };

    mItem.addActionListener(lst);

    mFile.add(mItem);

    mFile.addSeparator();

    mItem = new JMenuItem("Exit");

    mItem.setMnemonic('x');

    lst = new ActionListener() {

      public void actionPerformed(ActionEvent e) {

        if (JOptionPane.showConfirmDialog(

         DialogBoxes.this,

         "Do you want to quit this application ?",

         BOX_TITLE, JOptionPane.YES_NO_OPTION)

         == JOptionPane.YES_OPTION)

          System.exit(0);

      }

    };

    mItem.addActionListener(lst);

    mFile.add(mItem);

    menuBar.add(mFile);

    return menuBar;

  }

  public static void main(String argv[]) {

    new DialogBoxes();

  }

}

Understanding the Code

Class DialogBoxes

This class represents a simple frame which contains a menu bar created with our createMenuBar() method, and a JDesktopPane (see chapter 16) which is used as the frame's layered pane. The menu bar contains a single menu titled "File," which holds several menu items.

The createMenuBar() method is responsible for populating our frame's menu bar with seven menu items, each with an ActionListener to invoke the display of a JOptionPane in either a JDialog or JInternalFrame. The first menu item titled "Ask Question" creates an instance of JOptionPane, assigns it a custom icon using its setIcon() method, and custom option button Strings using setOptions(). A JDialog is created to hold this message box, and the show() method displays this dialog on the screen and waits until it is dismissed. At that point the getValue() method retrieves the user's selection as an Object, which may be null or one of the option button Strings assigned to this message box. The resulting dialog is shown in figure 14.6.

UI Guideline : Affirmative Text

The use of the affirmative and unambiguous text "To Be" and "Not to be" greatly enhances the usability of the option dialog. For example, were the text to have read, "To be or not to be? That is the question", "Yes" or "No", this would have been somewhat ambiguous and may have confused some users. The explicit text, "To Be", "Not to be" is much clearer.

This is another example of improved usability with just a little more extra coding effort.

The second menu item titled "nfo Message" creates a JOptionPane with a multi-line message String and a custom icon. The createInternalFrame() method is used to create a JInternalFrame holding the resulting JOptionPane message box. This internal frame is then added to the layered pane, which is now a JDesktopPane instance. The resulting internal frame is shown on the figure 14.7.

The third menu item titled "Error Message" produces a standard error message box using JOptionPane's static showMessageDialog() method and the ERROR_MESSAGE message type. The resulting dialog is shown in figure 14.8. Recall that JOptionPane dialogs appear, by default, centered with respect to the parent if the parent is a frame. This is why we don't do any manual positioning here.

The next two menu items titled "Text Input" and "Combobox Input" produce INFORMATION_MESSAGE JOptionPanes which take user input in a JTextField and JComboBox respectively. The static showInputDialog() is used to display these JOptionPanes in JDialogs. Figures 14.9 and 14.10 illustrate. The "Text Input" pane takes the initial text to display in its text field as a String parameter. The "Combobox Input" pane takes an array of Strings to display in the combo box as possible choices, as well as a String to display as initialy selected.

UI Guideline : Added Usability with Constrained Lists

Figures 14.9 and 14.10 clearly highlight how usability can be improved through effective component choice. The combobox with a constrained list of choices is clearly the better tool for the task at hand.

The Domain Problem in this example has a fixed number of choices. Shakespeare is clearly dead and the plays attributed to him are known. Thus the combobox in Fig 14.10 is a better choice. It should be populated with a list of all the known plays.

The Option Pane in Fig 14.9 would be better used for an unknown data entry such as "Please enter your name".

The final menu item titled "Exit" brings up a YES_NO_OPTION confirmation JOptionPane in a JDialog (shown in figure 14.11) by calling showConfirmDialog(). The application is terminated if the user answers "Yes."



[ Return to Swing (Book) ]


Top 10 read Java Articles
 Get free "1000 Java Tips eBook"

 Java Calendar and Date: good to know facts and code examples

 Array vs ArrayList vs LinkedList vs Vector: an excellent overview and examples

 How can I convert any Java Object into byte array? And byte array to file object

 The Java Lesson 1: What is Java?

 How do I compare two dates and times, date between dates, time between times and

 Maven vs Ant or Ant vs Maven?

 How to open, read, write, close file(s) in Java? Examples on move, rename and de

 Java Array

 Java: JLabel font and color


[ More in News Section ]
Java Lessons

The Java Lesson 1:
What is Java?
The Java Lesson 2:
Anatomy of a simple Java program
The Java Lesson 3:
Identifiers and primitive data types
The Java Lesson 4:
Variables, constants, and literals
The Java Lesson 5:
Arithmetic operations, conversions, and casts
The Java Lesson 6:
Boolean expressions and operations
The Java Lesson 7:
Bitwise operations
The Java Lesson 8:
Flow control with if and else
The Java Lesson 9:
switch statements
The Java Lesson 10:
for, while, and do-while statements
The Java Lesson 11:
Using break and continue
The Java Lesson 12:
Class methods and how they are called
The Java Lesson 13:
Using the Math class
The Java Lesson 14:
Creating and calling custom class methods
The Java Lesson 15:
Overloading class methods
The Java Lesson 16:
An introduction to objects and object references
The Java Lesson 17:
The String class
The Java Lesson 18:
The StringBuffer class
The Java Lesson 19:
Initializing and processing arrays of primitives
The Java Lesson 20:
Initializing and processing arrays of objects
The Java Lesson 23:
Inheritance and overriding inherited methods
The Java Lesson 24:
abstract classes and polymorphism
The Java Lesson 25:
Interfaces, instanceof, and object conversion and casting
The Java Lesson 26:
Introduction to graphical programming and the java.awt packa
The Java Lesson 27:
The Component class
The Java Lesson 28:
Containers and simple layout managers
The Java Lesson 29:
The Color and Font classes
The Java Lesson 30:
Drawing geometric shapes
The Java Lesson 31:
Choice, List, and Checkbox controls
The Java Lesson 32:
Using the Scrollbar graphical control
The Java Lesson 33:
Menus and submenus
The Java Lesson 34:
An introduction to applets and the Applet class
The Java Lesson 35:
Essential HTML to launch an applet and pass it parameters
The Java Lesson 36:
Mouse event processing
Java Lesson 37:
Menus and submenus
Java Lesson 38:
The WindowListener interface and the WindowAdapter class
Java Lesson 39:
An introduction to GridBagLayout
Java Lesson 40:
An introduction to the Java Collections API
Java Lesson 41:
Exception handling with try, catch, and finally blocks
Java Lesson 42:
Claiming and throwing exceptions
Java Lesson 43:
Multithreading, the Thread class, and the Runnable interface
Java Lesson 44:
An introduction to I/O and the File and FileDialog classes
Java Lesson 45:
Low-level and high-level stream classes
Java Lesson 46:
Using the RandomAccessFile class
Java Lessons by
Joh Huhtala: Update

Latest articles
 Java Profiler JProbe to Resolve Performance Problems Faster

 SSL with GlassFish v2, page 5

 SSL with GlassFish v2, page 4

 SSL with GlassFish v2, page 3

 SSL with GlassFish v2, page 2

 The Java Lesson 2: Anatomy of a simple Java program, page 2

 New site about Java for robots and robotics: both software and hardware.

 Exceptions -III: What's an exception and why do I care?

 Exceptions -II: What's an exception and why do I care?

 Exceptions: What's an exception and why do I care?

 Double your Java code quality in 10 minutes, here is receipt

 Murach's Java Servlets and JSP

 How to get ascii code from a char in Java?

 Can we just try without catch? Yes!

 Make Tomcat page load faster

 Make your Tomcat More secure - limit network address for certain IP addresses

 New Java book online starts now here...

 Implementing RESTful Web Services in Java

 Firefox trimming from 1 GB to 40 Mb with many tabs opened

 SSL with GlassFish v2

 My request to replublish Tech Tips

 Search JavaFAQ.nu site here

 New Advanced Installer for Java 6.0 brings XML updates and imports 3rd party MSI

 EJB programming restrictions

 Maven vs Ant or Ant vs Maven?

 Why Java does not use default value which it should?

 How to unsign signed bytes in Java - your guide is here

 The Java Lesson 3: Identifiers and primitive data types. Page 2

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 4

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 3


[ More in News Section ]


Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy