Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading