O'Reilly logo

Java Swing by Dave Wood, Marc Loy, Robert Eckstein

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

The JOptionPane Class

JOptionPane is a utility class used to create complex JDialog and JInternalFrame (for use as lightweight dialogs) objects. Figure 10.2 shows where JOptionPane fits into the class hierarchy; Figure 10.2 shows JOptionPane in the three look-and-feels. It provides a range of convenient ways to create common popup dialog boxes, significantly reducing the amount of code you are required to write.

The JOptionPane class hierarchy

Figure 10-2. The JOptionPane class hierarchy

JOptionPanes (showing internal confirm dialogs) in the three look-and-feels

Figure 10-3. JOptionPanes (showing internal confirm dialogs) in the three look-and-feels

For example, to create a very simple dialog window with the text “Click OK after you read this” and an “OK” button without JOptionPane, you’d have to write something like the code that follows.

public void showSimpleDialog(JFrame f) { final JDialog d = new JDialog(f, "Click OK", true); d.setSize(200, 150); JLabel l = new JLabel("Click OK after you read this", JLabel.CENTER); d.getContentPane().setLayout(new BorderLayout()); d.getContentPane().add(l, BorderLayout.CENTER); JButton b = new JButton("OK"); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { d.setVisible(false); d.dispose(); } }); JPanel p = new JPanel(); // flow layout will center button p.add(b); d.getContentPane().add(p, BorderLayout.SOUTH); d.setLocationRelativeTo(f); ...

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