O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Dialogs: When Later Just Won’t Do

Problem

You need a bit of feedback from the user right now.

Solution

Use a JOptionPane method to show a prebuilt dialog.

Discussion

It’s fairly common to want to confirm an action with the user or to bring some problem to their attention right away, rather than waiting for them to read a logfile that they might or might not get around to. These pop-up windows are called Dialogs. The JOptionPane class has a number of show...Dialog( ) methods that let you display most prebuilt dialogs, including those shown in Figure 13-6.

JOptionPane in action

Figure 13-6. JOptionPane in action

The simplest form is showMessageDialog( ), and its first argument is the owning Frame or JFrame. If you don’t know it, pass null, but Java doesn’t guarantee to give input focus back to your main window when the dialog is dismissed. The second argument is the message text, and the third is the title bar title. Last but not least is code telling which of several prebuilt bitmaps should be displayed. This program produces the “Coded Message” dialog in the figure:

import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * Demonstrate JOptionPane */ 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( ) { ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required