10.4 Simple Examples


The following are a few examples that show some of things you can do with JOptionPane static methods and constructors.

Here's an input dialog with more than 20 selection values. This results in the creation of a JList (Figure 10-8):

JOptionPane.showInputDialog(null, "Please choose a name", "Example 1",   JOptionPane.QUESTION_MESSAGE, null, new Object[] {     "Amanda", "Colin", "Don", "Fred", "Gordon", "Janet", "Jay", "Joe",     "Judie", "Kerstin", "Lotus", "Maciek", "Mark", "Mike", "Mulhern",     "Oliver", "Peter", "Quaxo", "Rita", "Sandro", "Tim", "Will"}, "Joe");
Figure 10-8. Input dialog (JList)
figs/swng2.1008.gif

Here's another input dialog. This time, we don't provide any selection values, so we get a JTextField. The default value we supply is entered in the field when it comes up (Figure 10-9).

JOptionPane.showInputDialog(null, "Please enter your name", "Example 2",   JOptionPane.QUESTION_MESSAGE, null, null, "Shannon");
Figure 10-9. Input dialog (JTextField)
figs/swng2.1009.gif

Next, we'll try a message dialog with a custom icon (Figure 10-10):

JOptionPane.showMessageDialog(null, "Have a nice day.", "Example 3",   JOptionPane.INFORMATION_MESSAGE, new ImageIcon("images/smile.gif"));
Figure 10-10. Message dialog with a custom Icon
figs/swng2.1010.gif

Here's a very simple confirm dialog (Figure 10-11):

JOptionPane.showConfirmDialog(null, "Are you sure?", "Example 4",   JOptionPane.YES_NO_CANCEL_OPTION);
Figure 10-11. Confirm dialog
figs/swng2.1011.gif

Next, we'll get a little fancy and create an internal frame dialog with custom option buttons (Figure 10-12):

JOptionPane.showInternalOptionDialog(desk, "Please select a color",   "Example 5", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE,   null, new Object[] {"Red", "Green", "Blue"}, "Blue");
Figure 10-12. Internal frame dialog with custom buttons
figs/swng2.1012.gif

Finally, let's use a JOptionPane constructor and place the new pane inside a regular Swing container. This is a strange thing to do, but it's perfectly valid (Figure 10-13).

JFrame f = new JFrame( ); Container c = f.getContentPane( ); c.setLayout(new BorderLayout( )); JOptionPane op = new JOptionPane("Stop!", JOptionPane.WARNING_MESSAGE); JPanel p = new JPanel(new FlowLayout( )); p.add(op); c.add(p); c.add(new JLabel("Example 6", JLabel.CENTER), BorderLayout.NORTH); f.setVisible(true);
Figure 10-13. A JOptionPane inside a Swing container
figs/swng2.1013.gif


Java Swing
Graphic Java 2: Mastering the Jfc, By Geary, 3Rd Edition, Volume 2: Swing
ISBN: 0130796670
EAN: 2147483647
Year: 2001
Pages: 289
Authors: David Geary

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net