Dialog Box in Java Swing

The dialog box in Java Swing is a graphical user interface element used to display messages, gather user input, or prompt users to make decisions. Swing provides several types of dialog boxes to interact with users, such as message dialogs, input dialogs, and option dialogs.

Following is an example of how we can create and use different types of dialog boxes in Java Swing:

Message Dialog

A message dialog is used to display informative messages to the user.

Info Message

JOptionPane.showMessageDialog(null, "This is a message dialog.", "Info message", JOptionPane.INFORMATION_MESSAGE);

Output:

info message in joption pane swing

Error Message

JOptionPane.showMessageDialog(null, "This is a message dialog.", "Error message", JOptionPane.ERROR_MESSAGE);

Output:

error message in joption pane swing

Warning Message

JOptionPane.showMessageDialog(null, "This is a message dialog.", "Warning message", JOptionPane.WARNING_MESSAGE);

Output:

warning message in joption pane swing

Plain Message

JOptionPane.showMessageDialog(null, "This is a message dialog.", "Plain message", JOptionPane.PLAIN_MESSAGE);

Output:

plain message in joption pane swing

Custom Icon Message

Display custom Icon from URL:

try {
	ImageIcon customIcon = new ImageIcon(
					new URL("https://example.com/myicon.png"));
	JOptionPane.showMessageDialog(null, "This is a message dialog.", "Custom Icon message",
	JOptionPane.PLAIN_MESSAGE, customIcon);
} catch (MalformedURLException e) {
	e.printStackTrace();
}

Display custom icon from a local file path:

ImageIcon customIcon = new ImageIcon("C:\\Users\\codersathi\\Pictures\\mylogo.png");
JOptionPane.showMessageDialog(null, "This is a message dialog.", "Custom Icon message",
					JOptionPane.PLAIN_MESSAGE, customIcon);

Output:

custom icon in joption pane swing

Option Dialog

An option dialog displays a message along with multiple options for the user to choose from. For example, let’s see the following code and output:

Object[] options = { "Physics", "Biology", "Mathematics", "Computer Science", "Humanities" };
		int n = JOptionPane.showOptionDialog(null, "Please select your option from the list below.",
				"Which subject do you study?", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null,
				options, options[2]);
// The following line prints the index value from the options when user clicks on that option
		System.out.println(n);

Output:

option dialog with custom button in joption swing java

When you click on this button, it will return the output value as an index of options array starting from 0 (zero). If you click on the X (close) icon then it will print -1.

Sharing Is Caring:
Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments