Search code examples
javaswingjoptionpane

Why is the message being created by an instance of JOptionPane not shown?


I wanted to show a message without using static methods of the JOptionPane class and here's a Java program using an object of the JOptionPane class to show a message.

import javax.swing.*;
public class Sample {
    public  static void main(String[] args) {
        JOptionPane pane = new JOptionPane();
        pane.setMessage("Hello");
        pane.setOptionType(JOptionPane.OK_OPTION);
        pane.setName("Information");
        pane.setVisible(true);
    }
}

It's expected to show a message, but nothing is shown as the result when it gets compiled and run. What's the problem?


Solution

  • Per the JOptionPane API, JOptionPane extends from JComponent, and so by itself, a JOptionPane object is not a top-level window, and so is not visible on its own, even if setVisible(true) is called. To create a visible window from a JOptionPane object, you must create a JDialog from your JOptionPane object. either that or place it within another container that is eventually displayed within a top-level window (as per any JComponent-type object). For example, and lifted directly from the API:

     JOptionPane pane = new JOptionPane(arguments);
     pane.set.Xxxx(...); // Configure
     JDialog dialog = pane.createDialog(parentComponent, title);
     dialog.setVisible(true);
    

    In my opinion, however, it is simpler and better to just use the static methods to create and display a JOptionPane within its own JDialog.