Recipe 14.7 Dialogs: When Later Just Won't DoProblemYou need a bit of feedback from the user right now. SolutionUse a JOptionPane method to show a prebuilt dialog. Or subclass JDialog. DiscussionIt's fairly common to want to confirm an action with the user or to bring some problem to her attention right away, rather than waiting for her to read a log file that she might or might not get around to. These popup 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 14-6. Figure 14-6. JOptionPane in actionThe 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 titlebar 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( ) { 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); // the main window setSize(200, 150); pack( ); } public static void main(String[] arg) { JOptionDemo x = new JOptionDemo("Testing 1 2 3..."); x.setVisible(true); } } You can use the JOptionPane class in several other ways. For example, you can call its showDialog( ) method with a list of strings; each is displayed on a push button in the dialog. This method blocks until the user selects one of the buttons; the return value of the method is an int telling which button the user clicked on (it returns the array index of the string whose button was pressed). Another method, showInputDialog( ) , lets you prompt the user for a data value. Very, very convenient! See AlsoJDialog lets you write arbitrarily complicated dialogs. You subclass them in a manner similar to JFrame, specifying whether you want an application-modal or nonmodal dialog (a modal dialog locks out the rest of the application, which is less convenient for the user but much easier for the programmer). See Java Swing (O'Reilly) for information on JDialog. |