Search code examples
javaswingjlabeljoptionpanejdialog

JDialog does not display proper text


I'm creating an About dialog for my program and have run into an issue. Whenever I launch the dialog, the title text sets properly, but the text inside the dialog says "JOptionPane Message". Before it wouldn't even show the label I added to the dialog, but that fixed itself (I'm not entirely sure how) but now it displays both the added text and the "JOptionPane Message".

Code for the dialog:

    about.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            JOptionPane optionPane = new JOptionPane();
            JDialog dialog = optionPane.createDialog("About");
            JLabel aboutText = new JLabel("Text goes here", JLabel.CENTER);
            dialog.add(aboutText, BorderLayout.NORTH);
            dialog.setVisible(true);
        }
    });

So the text works now, which is nice. But how do I get rid of the part that says "JOptionPane Message"?


Solution

  • Here's what you do to procure the about dialog. Plus, it's only one line of code!

    JOptionPane.showMessageDialog(this, "Text goes here", "About", JOptionPane.INFORMATION_MESSAGE);
    

    I assume that this code is inside a subclass of JFrame. If not, replace this with any component inside the window where you want to dialog to appear, or just null for the center of the screen.

    You may also want to change "Text goes here" to your own custom message text.

    To change the type of message, change JOptionPane.INFORMATION_MESSAGE to one of the following:

    • JOptionPane.ERROR_MESSAGE
    • JOptionPane.WARNING_MESSAGE
    • JOptionPane.QUESTION_MESSAGE
    • JOptionPane.PLAIN_MESSAGE