O'Reilly logo

Java Swing, 2nd Edition by Brian Cole, James Elliott, Marc Loy, Robert Eckstein, Dave Wood

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

A Comparison: Constructors Versus Static Methods

We’ve talked quite a bit about the two fundamental ways to create dialogs using JOptionPane: instantiate a JOptionPane and ask it to put itself into a JDialog or JInternalFrame, which you then display, or create and display the dialog in a single step by invoking one of the many static “show” methods.

The basic trade-off is this: using the static methods is a bit easier, but using a constructor allows you to hold onto and reuse the JOptionPane instance, a tempting feature if the pane is fairly complex and you expect to display it frequently (if you use the static methods, the option pane is recreated each time you call). The significance of this difference depends largely on the complexity of the pane. Because of lingering issues that make reusing JOptionPane problematic, it’s still best to avoid this feature (see the note in the discussion following this example program for details).

The following example shows the differences between using JOptionPane’s static methods and its constructors. It allows both internal and noninternal dialogs to be created, showing how each is done.

// OptPaneComparison.java // import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.beans.*; public class OptPaneComparison extends JFrame { public static void main(String[] args) { JFrame f = new OptPaneComparison("Enter your name"); f.setVisible(true); } public OptPaneComparison(final String message) { setDefaultCloseOperation(EXIT_ON_CLOSE); ...

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