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.
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( ) { ...
Get Java Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.