Quantcast
Channel: Digitivity » HowTo
Viewing all articles
Browse latest Browse all 10

How to Show a MessageBox in Java Swing

$
0
0

VisualBasic and a lot of other languages have a handy function to show a message box to the user. In typical Java fashion, Java’s equivalent has a lot more power, but also complex.

To get simple message box functionality, you have to specify a number of options:

JOptionPane.showMessageDialog(parent,
    "Message",
    "Title",
    JOptionPane.INFORMATION_MESSAGE,
    icon);

This shows a dialog with your message plus a look-and-feel defined icon which varies depending on the option selected. For example, a question mark icon is shown for JOptionPane.QUESTION_MESSAGE. The various message types are shown below for the default Swing Metal look-and-feel:

Java Swing MessageBox: PLAIN_MESSAGE

Java Swing MessageBox: PLAIN_MESSAGE

Java Swing MessageBox: INFORMATION_MESSAGE

Java Swing MessageBox: INFORMATION_MESSAGE

Java Swing MessageBox: QUESTION_MESSAGE

Java Swing MessageBox: QUESTION_MESSAGE

Java Swing MessageBox: WARNING_MESSAGE

Java Swing MessageBox: WARNING_MESSAGE

Java Swing MessageBox: ERROR_MESSAGE

Java Swing MessageBox: ERROR_MESSAGE

Note: the icon can be null if you don’t want or need an icon. You should specify a parent component (such as a JFrame) if you want the dialog to be modal with respect to that component. If you don’t mind that the user can click on something else and ignore your dialog message, leave it null.

If you want to get a response from the user as opposed to simply having him click OK, use the JOptionPane.showConfirmDialog() series of methods.

Related posts:

  1. How to Add an E-mail to a Gravatar Account
  2. How to Install Java on Windows
  3. VLC Reverts to Normal Without the Santa Hat After New Year

Viewing all articles
Browse latest Browse all 10

Trending Articles