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");
Input dialog (JList)

Figure 10-8. Input dialog (JList)

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");
Input dialog (JTextField)

Figure 10-9. Input dialog (JTextField)

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"));
Message dialog with a custom Icon

Figure 10-10. Message dialog with a custom Icon ...

Get Java Swing, 2nd Edition 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.