53

How to open warning/information/error dialog in Swing?

I need standard error dialog with "Ok" button and "red cross" image. I.e. analog of org.eclipse.jface.dialogs.MessageDialog.openError()

4 Answers 4

85

See How to Make Dialogs.

You can use:

JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green.");

And you can also change the symbol to an error message or an warning. E.g see JOptionPane Features.

1
  • 2
    Make sure you dispose the frame, or pass null as the frame. If you don't it could hold your process open.
    – ScrappyDev
    Commented Feb 24, 2017 at 15:47
27
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class ErrorDialog {

  public static void main(String argv[]) {
    String message = "\"The Comedy of Errors\"\n"
        + "is considered by many scholars to be\n"
        + "the first play Shakespeare wrote";
    JOptionPane.showMessageDialog(new JFrame(), message, "Dialog",
        JOptionPane.ERROR_MESSAGE);
  }
}
1
  • although this works this doesnt close the program once you hit ok can you add some info on that
    – Buddhi741
    Commented Sep 18, 2018 at 12:20
9
JOptionPane.showOptionDialog
JOptionPane.showMessageDialog
....

Have a look on this tutorial on how to make dialogs.

0
4

Just complementing, you can use static imports to give you a hand, making the code cleaner, like this:

import static javax.swing.JOptionPane.*;

public class SimpleDialog(){
    public static void main(String argv[]) {
        showMessageDialog(null, "Message", "Title", ERROR_MESSAGE);
    }
}
3
  • 1
    plz if you are going to tell people something like "It's kind of obvious", just don't bother writing an answer. nobody knows the exact same things you do and neither does anybody have to.
    – Adnan
    Commented Oct 17, 2021 at 15:39
  • 1
    this is literally my first SO post.
    – Ramon Dias
    Commented Oct 18, 2021 at 12:14
  • 1
    thx for editing the answer.
    – Adnan
    Commented Oct 18, 2021 at 14:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.