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); ...

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.