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()
Jonas
117k96 gold badges305 silver badges381 bronze badges
asked Jun 7, 2011 at 19:10
![]()
Oleg VazhnevOleg Vazhnev
22.8k54 gold badges163 silver badges299 bronze badges
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.
answered Jun 7, 2011 at 19:12
1
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 ben"
+ "the first play Shakespeare wrote";
JOptionPane.showMessageDialog(new JFrame(), message, "Dialog",
JOptionPane.ERROR_MESSAGE);
}
}
answered Jun 11, 2014 at 13:36
Said ErraoudySaid Erraoudy
1,4601 gold badge13 silver badges20 bronze badges
1
JOptionPane.showOptionDialog
JOptionPane.showMessageDialog
....
Have a look on this tutorial on how to make dialogs.
answered Jun 7, 2011 at 19:13
HeisenbugHeisenbug
38.5k28 gold badges132 silver badges186 bronze badges
0
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);
}
}
answered Oct 27, 2017 at 12:50
Ramon DiasRamon Dias
7042 gold badges9 silver badges20 bronze badges
3
Афоризм
Честь девичью блюла, но не со всеми.
Наталья Резник
Поддержка проекта
Если Вам сайт понравился и помог, то будем признательны за Ваш «посильный» вклад в его поддержку и развитие
• Yandex.Деньги
410013796724260
• Webmoney
R335386147728
Z369087728698
Библиотека Swing включает богатый выбор стандартных диалоговых окон, существенно упрощающих и
ускоряющих вывод простой информации типа сообщений о работе программы, ошибках и нестандартных
ситуациях. Для вывода в графический интерфейс приложения разнообразной информации и выбора простых
данных предназначен класс JOptionPane, работа с которым связана с вызовом одного из многочисленных
статических методов, создающих и выводящих на экран модальное диалоговое окно стандартного вида.
В диалоговых окнах JOptionPane можно выводить самую разнообразную информацию и,
при необходимости, размещать в них дополнительные компоненты.
JOptionPane унаследован от базового класса JComponent библиотеки Swing, так что можно работать
с ним напрямую, т.е. создавать экземпляры класса JOptionPane и настраивать их свойства.
Использование стандартных диалоговых окон существенно упрощает разработку приложения и позволяет ускорить
процесс освоения пользователем интерфейса.
Все стандартные диалоговые окна Swing имеют собственные UI-представители, отвечающие за интерфейс
окна в используемом приложении. Это особенно важно для внешних видов окон, имитирующих известные
платформы, пользователи которых не должны ощущать значительной разницы при переходе от «родных»
приложений к Java-приложениям.
Класс JOptionPane
Интерфейс экземпляра класса JOptionPane имеет структуру, представленную на следующем рисунке.
Иконка в интерфейсе может отсутствовать.

Основные диалоговые методы JOptionPane
| Наименование метода | Описание |
|---|---|
| showMessageDialog | Диалоговое окно вывода сообщения |
| showConfirmDialog | Диалоговое окно подтверждения, с включением кнопок типа yes/no/cancel |
| showInputDialog | Диалоговое окно с выбором |
Конструкторы окна сообщений showMessageDialog
// Простое диалоговое окно с заголовком «Message»
public static void showMessageDialog(Component parent,
Object message)
throws HeadlessException
// Диалоговое окно с заголовком и типом сообщения
public static void showMessageDialog(Component parent,
Object message,
String title,
int messageType)
throws HeadlessException
// Диалоговое окно с заголовком, типом сообщения и иконкой
public static void showMessageDialog(Component parent,
Object message,
String title,
int messageType,
Icon icon)
throws HeadlessException
Конструкторы окна подтверждения showConfirmDialog
// Простое диалоговое окно подтверждения с кнопками Yes, No, Cancel и
// с заголовком «Select an Option»
public static void showConfirmDialog(Component parent,
Object message)
throws HeadlessException
// Окно подтверждения с заголовком и кнопками, определенными
// опцией optionType
public static void showConfirmDialog(Component parent,
Object message,
String title,
int optionType)
throws HeadlessException
// Окно подтверждения с заголовком, кнопками, определенными
// опцией optionType, и иконкой
public static void showConfirmDialog(Component parent,
Object message,
String title,
int optionType,
Icon icon)
throws HeadlessException
Конструкторы окна выбора showInputDialog
// Диалоговое окно с полем ввода
public static void showInputDialog(Component parent,
Object message)
throws HeadlessException
// Диалоговое окно с полем ввода, инициализируемое initialSelectionValue
public static void showInputDialog(Component parent,
Object message,
Object initialSelectionValue)
throws HeadlessException
// Диалоговое окно с полем выбора из списка selectionValues
public static void showInputDialog(Component parent,
Object message,
String title,
int messageType,
Icon icon,
Object[] selectionValues,
Object initialSelectionValue)
throws HeadlessException
parent — родительское окно.
message — отображаемый в окне текст сообщения. В большинстве случаев это строка, но может
быть использован массив строк String[], компонент Component, иконка Icon, представленная меткой
JLabel, объект Object, конвертируемый в строку методом toString().
title — заголовок окна.
messageType — тип диалогового окна :
- INFORMATION_MESSAGE — стандартное диалоговое окно для вывода информации со значком
соответствующего вида; - WARNING_MESSAGE — стандартное диалоговое окно для вывода предупреждающей информации
со значком соответствующего вида; - QUESTION_MESSAGE — стандартное диалоговое окно для вывода информации. Как правило,
не используется для информационных сообщений; - ERROR_MESSAGE — стандартное диалоговое окно для вывода информации об ошибке со значком
соответствующего вида; - PLAIN_MESSAGE — стандартное диалоговое окно для вывода информации без значка.
optionType — опция определения кнопок управления :
- DEFAULT_OPTION
- YES_NO_OPTION
- YES_NO_CANCEL_OPTION
- OK_CANCEL_OPTION
selectionValues — список возможных значений. В диалоговом окне InputDialog список
будет представлен в компоненте JComboBox или JList. Если selectionValues = null, то в окне
будет определено поле JTextField, в которое пользователь может ввести любое значение.
initialSelectionValue — инициализируемое значение.
icon — отображаемая в диалоговом окне иконка.
Локализация кнопок JOptionPane
Кнопки управления, как правило, имеют заголовки «Yes», «No», «Cancel». Для локализации кнопок
диалогового компонента JOptionPane можно использовать UIManager
следующим образом :
UIManager.put("OptionPane.yesButtonText" , "Да" );
UIManager.put("OptionPane.noButtonText" , "Нет" );
UIManager.put("OptionPane.cancelButtonText", "Отмена");
UIManager.put("OptionPane.okButtonText" , "Готово");
Пример использования JOptionPane
Пример JOptionPaneTest.java включает использование всех типов диалоговых
окон JOptionPane. В интерфейсе окна, представленном на следующем скриншоте, размещаются
кнопки, по нажатию на которые формируются соответствующие диалоговые окна JOptionPane.

Листинг примера JOptionPane
// Пример использования диалоговых окон JOptionPane
import javax.swing.*;
import java.awt.event.*;
public class JOptionPaneTest extends JFrame
{
private JPanel contents = null;
private JButton btnMessage1 = null;
private JButton btnMessage2 = null;
private JButton btnMessage3 = null;
private JButton btnConfirm1 = null;
private JButton btnConfirm2 = null;
private JButton btnConfirm3 = null;
private JButton btnInput1 = null;
private JButton btnInput2 = null;
private JButton btnInput3 = null;
private ImageIcon icon = null;
private final String TITLE_message = "Окно сообщения";
private final String TITLE_confirm = "Окно подтверждения";
private String[] drink = {"Сок",
"Минералка",
"Лимонад" ,
"Пиво"};
public JOptionPaneTest()
{
super("Пример использования JOptionPane");
setDefaultCloseOperation(EXIT_ON_CLOSE);
// Локализация кнопок
UIManager.put("OptionPane.yesButtonText" , "Да" );
UIManager.put("OptionPane.noButtonText" , "Нет" );
UIManager.put("OptionPane.cancelButtonText", "Отмена");
contents = new JPanel();
// Иконка для отображения в окне сообщений
icon = new ImageIcon("images/warning.png");
// Кнопка формирования окна по 2-м параметрам
btnMessage1 = new JButton("MessageDialog 2");
// Кнопка формирования окна по 4-м параметрам
btnMessage2 = new JButton("MessageDialog 4");
// Кнопка формирования окна по 5-и параметрам
btnMessage3 = new JButton("MessageDialog 5");
// Кнопки вывода сообщений подтверждения
btnConfirm1 = new JButton("ConfirmDialog 4+2");
btnConfirm2 = new JButton("ConfirmDialog 5");
btnConfirm3 = new JButton("ConfirmDialog 6");
btnInput1 = new JButton("InputDialog 2+3");
btnInput2 = new JButton("InputDialog 4");
btnInput3 = new JButton("InputDialog 7");
addMessageListeners();
addConfirmListeners();
addInputListeners ();
// Размещение кнопок в интерфейсе
contents.add(btnMessage1);
contents.add(btnMessage2);
contents.add(btnMessage3);
contents.add(btnConfirm1);
contents.add(btnConfirm2);
contents.add(btnConfirm3);
contents.add(btnInput1);
contents.add(btnInput2);
contents.add(btnInput3);
setContentPane(contents);
// Вывод окна на экран
setSize(500, 140);
setVisible(true);
}
}
В методах addMessageListeners(), addConfirmListeners(),
addInputListeners() определяются слушатели, обрабатывающие нажатие соответствующих
кнопок.
Окна вывода сообщений MessageDialog
Листинг процедуры создания слушателей, формирующие диалоговые окна вывода сообщений.
private void addMessageListeners()
{
btnMessage1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(JOptionPaneTest.this,
"<html><h2>Текст</h2><i>в виде разметки HTML</i>");
}
});
btnMessage2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(JOptionPaneTest.this,
new String[] {"Сообщение в виде массива строк :",
" - первая строка",
" - вторая строка"},
TITLE_message,
JOptionPane.ERROR_MESSAGE);
}
});
btnMessage3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Включение в интерфейс иконки
JOptionPane.showMessageDialog(JOptionPaneTest.this,
"Использование изображения в окне сообщений",
TITLE_message, JOptionPane.INFORMATION_MESSAGE,
icon);
}
});
}
1. Интерфейс окна вывода сообщений по нажатию на кнопку btnMessage1. Конструктор
получает 2 параметра : родитель и текст сообщения. В заголовок подставляется значение «Message».
Текст сообщения имеет HTML разметку.

2. Интерфейс окна вывода сообщений по нажатию на кнопку btnMessage2. Конструктор
получает 4 параметра : родитель, текст сообщения в виде массива строк, строку заголовка окна и
тип сообщения.

3. Интерфейс окна вывода сообщений по нажатию на кнопку btnMessage2. Конструктор
получает 5 параметров : родитель, текст сообщения, строку заголовка окна, тип сообщения и иконку.

Диалоговые окна подтверждений ConfirmDialog
Листинг процедуры создания слушателей, формирующие диалоговые окна подтверждений.
private void addConfirmListeners()
{
btnConfirm1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Окно подтверждения c 4-мя параметрами
int result = JOptionPane.showConfirmDialog(
JOptionPaneTest.this,
"Вам это нужно?",
TITLE_confirm,
JOptionPane.YES_NO_CANCEL_OPTION);
// Окна подтверждения c 2-мя параметрами
if (result == JOptionPane.YES_OPTION)
JOptionPane.showConfirmDialog(JOptionPaneTest.this,
"Вы не отказываетесь?");
else if (result == JOptionPane.NO_OPTION)
JOptionPane.showConfirmDialog(JOptionPaneTest.this,
"Вы отказались?");
}
});
btnConfirm2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showConfirmDialog(JOptionPaneTest.this,
"Вы не отказываетесь?",
TITLE_confirm,
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
}});
btnConfirm3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showConfirmDialog(JOptionPaneTest.this,
"Вам нравится значок?",
TITLE_confirm,
JOptionPane.YES_NO_OPTION,
JOptionPane.ERROR_MESSAGE,
icon);
}});
}
1. Интерфейс окна подтверждения по нажатию на кнопку btnConfirm1. Конструктор
получает 4 параметра : родитель, текст сообщения, строка заголовка и опция кнопок управления

В зависимости от нажатой кнопки открываются следующее окно подтверждение (одно из окон на
следующем скриншот), конструктор которого получает 2 параметра. Текст заголовка имеет значение по
умолчанию «Select an Option».

2. Интерфейс окна подтверждения по нажатию на кнопку btnConfirm2. Конструктор
получает 5 параметров : родитель, текст сообщения, строка заголовка, опция кнопок управления и
тип сообщения.

3. Интерфейс окна подтверждения по нажатию на кнопку btnConfirm3. Конструктор
получает 6 параметров : родитель, текст сообщения, строка заголовка, опция кнопок управления,
тип сообщения и иконка.

Диалоговые окна выбора данных InputDialog
Листинг процедуры создания слушателей, формирующие диалоговые окна выбора
private void addInputListeners()
{
btnInput1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Диалоговое окно ввода данных : родитель, HTML сообщение
String result = JOptionPane.showInputDialog(
JOptionPaneTest.this,
"<html><h2>Добро пожаловать");
JOptionPane.showInputDialog(JOptionPaneTest.this,
"Вы ответили", result);
}
});
btnInput2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Диалоговое окно ввода данных : родитель, сообщение в виде
// массива строк, тип диалогового окна (иконки)
JOptionPane.showInputDialog(JOptionPaneTest.this,
new String[] {"Неверно введен пароль!",
"Повторите пароль :"},
"Авторизация",
JOptionPane.WARNING_MESSAGE);
}
});
btnInput3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Диалоговое окно ввода данных
Object result = JOptionPane.showInputDialog(
JOptionPaneTest.this,
"Выберите любимый напиток :",
"Выбор напитка",
JOptionPane.QUESTION_MESSAGE,
icon, drink, drink[0]);
// Диалоговое окно вывода сообщения
JOptionPane.showMessageDialog(JOptionPaneTest.this, result);
}
});
}
1. Интерфейс окна ввода данных по нажатию на кнопку btnInput1 представлен на скриншоте
слева. Конструктор получает 2 параметра : родитель и текст сообщения с разметкой HTML. После ввода
значения и нажатия на одну из клавиш открывается окно, представленное на скриншоте справа.

2. На следующем скриншоте представлен интерфейс окна ввода данных, создаваемое конструктором,
которому в качестве текста передается родитель, текстовое сообщение в виде массива строк, строка
заголовка и тип диалогового окна (иконки).

3. Интерфейс окна ввода данных по нажатию на кнопку btnInput3 представлен на следующем
скриншоте слева. Конструктор получает все возможные параметры : родитель, текстовое сообщение,
строка заголовка, тип диалогового окна, иконка, массив строк и выделенное значение по умолчанию.
В диалоговом окне возможные значения представлены в компоненте выпадающего списка. После выбора
значения и нажатия на одну из клавиш открывается окно вывода сообщения, представленное на
скриншоте справа.

Скачать примеры
Исходные коды примеров, рассмотренных на странице, можно
скачать здесь (2.25 Кб).
Following example showcase how to show an error message alert in swing based application.
We are using the following APIs.
-
JOptionPane − To create a standard dialog box.
-
JOptionPane.showMessageDialog() − To show the message alert.
-
JOptionPane.ERROR_MESSAGE − To mark the alert message as error.
Example
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SwingTester {
public static void main(String[] args) {
createWindow();
}
private static void createWindow() {
JFrame frame = new JFrame("Swing Tester");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createUI(frame);
frame.setSize(560, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void createUI(final JFrame frame){
JPanel panel = new JPanel();
LayoutManager layout = new FlowLayout();
panel.setLayout(layout);
JButton button = new JButton("Click Me!");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Please ensure compliance!",
"Swing Tester", JOptionPane.ERROR_MESSAGE);
}
});
panel.add(button);
frame.getContentPane().add(panel, BorderLayout.CENTER);
}
}
Output

swingexamples_dialogs.htm
Окно сообщения в Java — это всплывающее окно, которое появляется на экране для отображения какого-либо сообщения и ожидает подтверждения от пользователя. Термин JOptionPane — это предоставляемый Java класс, который предоставляет пользователям привилегию показывать диалоговые окна сообщений. Этот класс наследуется от класса JComponent и присутствует в пакете javax.swing.
Ниже приведен блок кода, показывающий, как работает окно сообщения в Java.
import javax.swing.*;
public class DialogueBoxPopUp {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null,
"Hi, In the message box",
"PopUp Dialog",
JOptionPane.INFORMATION_MESSAGE);
}
}
В приведенном выше простом блоке кода класс JOptionPane предлагает пользователям окна сообщений и ожидает ответа. В классе есть несколько статических методов, которые служат для пользователя служебными программами. Метод showConfirmDialog задает вопрос и подтверждает варианты да, нет и отмена. Метод showInputDialog предлагает пользователю ввести некоторые данные. Функция showMessageDialog сообщает пользователю о некоторых событиях.
Вышеупомянутый блок использует перегруженную версию метода showMessageDialog и принимает четыре параметра. Во-первых, аргумент parentComponent проверяет фрейм, в котором может отображаться компонент. Если значение является нулевым значением, то используется фрейм по умолчанию. В предыдущей программе передается нулевой фрейм, поэтому код использует фрейм по умолчанию.
Далее идет аргумент message, который выводит на экран сообщение Object. Аргумент title принимает строку заголовка для всплывающего окна. Сообщение в приведенном выше блоке имеет заголовок Всплывающее диалоговое окно, которое появляется в верхней части диалогового окна.
messageType — это тип сообщения, которое выполняет значения ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE или PLAIN_MESSAGE. Эти значения представлены как статические и конечные значения как тип сообщения в классе JOptionPane. Код использует INFORMATION_MESSAGE в качестве типа сообщения.
Проверьте результат предыдущей программы здесь:

Если тип сообщения изменится на JOptionPane.ERROR_MESSAGE, появится диалоговое окно сообщения об ошибке, как на изображении ниже.

Если тип сообщения изменится на JOptionPane.WARNING_MESSAGE, диалоговое окно с предупреждением будет выглядеть, как показано ниже.

Есть еще несколько типов сообщений, которые можно использовать при необходимости.
Содержание
- 1 1. Компонент и объект
- 2 2. Компонент, объект, строка и int
- 3 3. Компонент, объект, строка, int и значок
- 4 4. Более сложный пример
- 5 Рекомендации
Это обзор showMessageDialog() метод JOptionPane Учебный класс. Этот метод — быстрый и простой способ рассказать пользователю о том, что произошло. showMessageDialog() Можно вызвать с помощью следующих комбинаций параметров:
Component, Object
Component, Object, String, int
Component, Object, String, int, Icon
- Компонент — первый параметр — это компонент, который определяет фрейм, в котором отображается диалоговое окно; если ноль, или если
parentComponentне имеет рамки, используется рамка по умолчанию. - Объект — вторым параметром могут быть любые объекты. (В некоторых старых версиях Java вы можете получить ошибку компилятора при непосредственном использовании примитивных типов) .
- String — Третий параметр — это строка, помещаемая в качестве заголовка диалогового окна сообщения.
- int — int, следующий за String, является
MessageType, РазныеMessageTypesзаJOptionPane, являются:- СООБЩЕНИЕ ОБ ОШИБКЕ
- INFORMATION_MESSAGE
- ПРЕДУПРЕЖДАЮЩЕЕ СООБЩЕНИЕ
- QUESTION_MESSAGE
- PLAIN_MESSAGE
- Значок — последний параметр
Iconкоторый отображается внутри диалога и переопределяет значение по умолчаниюMessageTypeзначок.
1. Компонент и объект
Самый простой способ использовать диалог сообщений. Пример с Component установить на ноль и String в качестве второго аргумента:
SimpleDialog1.java
package com.csharpcoderr.messageDialog;
import javax.swing.JOptionPane;
public class SimpleDialog1 {
public static void main(String[] args){
JOptionPane.showMessageDialog(null, "Simple Information Message");
}
}
Выход:

2. Компонент, объект, строка и int
Добавление дополнительной информации в диалог сообщения. Пример с Component установить на ноль и double как второй параметр:
SimpleDialog2a.java
package com.csharpcoderr.messageDialog;
import javax.swing.JOptionPane;
public class SimpleDialog2a {
public static void main(String[] args){
JOptionPane.showMessageDialog(null, 8.9, "This is not an integer.", JOptionPane.PLAIN_MESSAGE);
}
}
Выход:

Пример сообщения об ошибке ( Component установить на ноль, String Object ):
SimpleDialog2b.java
package com.csharpcoderr.messageDialog;
import javax.swing.JOptionPane;
public class SimpleDialog2b {
public static void main(String[] args){
JOptionPane.showMessageDialog(null, "Uh-oh!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
Выход:

3. Компонент, объект, строка, int и значок
Сделайте ваше сообщение более красивым. Пример с Icon извлекается из каталога:
SimpleDialog3a.java
package messageDialog;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class SimpleDialog3a {
public static void main(String[] args){
ImageIcon icon = new ImageIcon("src/images/turtle64.png");
JOptionPane.showMessageDialog(null, "I like turtles.",
"Customized Dialog", JOptionPane.INFORMATION_MESSAGE, icon);
}
}
Выход:

Пример с Component установить на frame :
MessageDialogInFrame.java
package com.csharpcoderr.messageDialog;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.awt.Color;
public class MessageDialogInFrame extends JFrame{
public MessageDialogInFrame() {
getContentPane().setBackground(Color.DARK_GRAY);
setTitle("Message Dialog in Frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setResizable(false);
setSize(400, 300);
getContentPane().setLayout(null);
}
public static void main(String[] args){
ImageIcon icon = new ImageIcon("src/images/turtle64.png");
JOptionPane.showMessageDialog(new MessageDialogInFrame(),
"I appear as part of the frame!!", "Customized Dialog",
JOptionPane.INFORMATION_MESSAGE, icon);
}
}
Выход:

4. Более сложный пример
Для этого примера мы передаем JPanel в качестве параметра объекта. JPanel настроен и имеет JLabel добавил к этому. Мы также манипулируем размером OptionPane используя вызов UIManager ,
MessageDialogPanel.java
package com.csharpcoderr.messageDialog;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
public class MessageDialogPanel {
public static void main(String[] args){
ImageIcon icon = new ImageIcon("src/images/turtle64.png");
JPanel panel = new JPanel();
panel.setBackground(new Color(102, 205, 170));
panel.setSize(new Dimension(200, 64));
panel.setLayout(null);
JLabel label = new JLabel("Turtles are awesome!!! :D");
label.setBounds(0, 0, 200, 64);
label.setFont(new Font("Arial", Font.BOLD, 11));
label.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(label);
UIManager.put("OptionPane.minimumSize",new Dimension(300, 120));
JOptionPane.showMessageDialog(null, panel, "Customized Message Dialog", JOptionPane.PLAIN_MESSAGE, icon);
}
}
Выход:

Рекомендации
- Как сделать диалоги
- Класс JOption Pane — Java 8 API
диалоговое окно JOptionPane swing
Java Swing — пример showMessageDialog из JOptionPane
0.00 (0%) votes
Java Swing — пример JOptionPane showMessageDialog
Это обзор методаshowMessageDialog() классаJOptionPane. Этот метод — быстрый и простой способ рассказать пользователю о том, что произошло. showMessageDialog() можно вызвать с помощью следующих комбинаций параметров:
Component, Object Component, Object, String, int Component, Object, String, int, Icon
-
Компонент — первый параметр — это компонент, который определяет фрейм, в котором отображается диалог; если null, или если
parentComponentне имеет фрейма, используется фрейм по умолчанию. -
Объект — вторым параметром могут быть любые объекты. (In some older
versions of Java you might get a compiler error when using primitive
types directly). -
String — Третий параметр — это строка, помещенная в заголовок диалогового окна сообщения.
-
int — int, следующий за строкой, — это
MessageType. РазличныеMessageTypesдляJOptionPane:-
СООБЩЕНИЕ ОБ ОШИБКЕ
-
INFORMATION_MESSAGE
-
ПРЕДУПРЕЖДЕНИЕ
-
QUESTION_MESSAGE
-
PLAIN_MESSAGE
-
-
Значок — последний параметр — это
Icon, который отображается внутри диалогового окна и заменяет значок по умолчаниюMessageType.
1. Компонент и объект
Самый простой способ использовать диалог сообщения. Пример сComponent, установленным в ноль, иString в качестве второго аргумента:
SimpleDialog1.java
package com.techfou.messageDialog;
import javax.swing.JOptionPane;
public class SimpleDialog1 {
public static void main(String[] args){
JOptionPane.showMessageDialog(null, "Simple Information Message");
}
}
Выход:

2. Компонент, объект, строка и интервал
Добавление дополнительной информации в диалоговое окно сообщения. Пример сComponent, установленным в ноль, иdouble в качестве второго параметра:
SimpleDialog2a.java
package com.techfou.messageDialog;
import javax.swing.JOptionPane;
public class SimpleDialog2a {
public static void main(String[] args){
JOptionPane.showMessageDialog(null, 8.9, "This is not an integer.", JOptionPane.PLAIN_MESSAGE);
}
}
Выход:

Пример сообщения об ошибке (дляComponent установлено значение null,String Object):
SimpleDialog2b.java
package com.example.messageDialog;
import javax.swing.JOptionPane;
public class SimpleDialog2b {
public static void main(String[] args){
JOptionPane.showMessageDialog(null, "Uh-oh!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
Выход:

3. Компонент, объект, строка, интервал и значок
Сделайте диалог вашего сообщения «красивее». Пример сIcon, полученным из каталога:
SimpleDialog3a.java
package messageDialog;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class SimpleDialog3a {
public static void main(String[] args){
ImageIcon icon = new ImageIcon("src/images/turtle64.png");
JOptionPane.showMessageDialog(null, "I like turtles.",
"Customized Dialog", JOptionPane.INFORMATION_MESSAGE, icon);
}
}
Выход:

Пример сComponent, установленным наframe:
MessageDialogInFrame.java
package com.example.messageDialog;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.awt.Color;
public class MessageDialogInFrame extends JFrame{
public MessageDialogInFrame() {
getContentPane().setBackground(Color.DARK_GRAY);
setTitle("Message Dialog in Frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setResizable(false);
setSize(400, 300);
getContentPane().setLayout(null);
}
public static void main(String[] args){
ImageIcon icon = new ImageIcon("src/images/turtle64.png");
JOptionPane.showMessageDialog(new MessageDialogInFrame(),
"I appear as part of the frame!!", "Customized Dialog",
JOptionPane.INFORMATION_MESSAGE, icon);
}
}
Выход:

4. Более сложный пример
В этом примере мы передаемJPanel в качестве параметра Object. JPanel настраивается, и к нему добавляетсяJLabel. Мы также манипулируем размеромOptionPane с помощью вызоваUIManager.
MessageDialogPanel.java
package com.example.messageDialog;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
public class MessageDialogPanel {
public static void main(String[] args){
ImageIcon icon = new ImageIcon("src/images/turtle64.png");
JPanel panel = new JPanel();
panel.setBackground(new Color(102, 205, 170));
panel.setSize(new Dimension(200, 64));
panel.setLayout(null);
JLabel label = new JLabel("Turtles are awesome!!! :D");
label.setBounds(0, 0, 200, 64);
label.setFont(new Font("Arial", Font.BOLD, 11));
label.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(label);
UIManager.put("OptionPane.minimumSize",new Dimension(300, 120));
JOptionPane.showMessageDialog(null, panel, "Customized Message Dialog", JOptionPane.PLAIN_MESSAGE, icon);
}
}
Выход:

This post describe about the MessageBox of java, If you want to show message box, you have to use jOptionPane class to handle message dialog box. you will find many customization option in jOptionPane in Java according to requirement. You can simply choose what type of message Dialog you want to show in your project.
So, in this post SKOTechLearn will describe the process of showing different types of messages through jOptionPane in java Swing NetBeans.
What is jOptionPane in Java?
It is simply a message box in which you can define a message and show in different types as we learn in this post.
There are following types of jOptionPane dialog appearance that we will learn:
- Show simple Plain MessageBox in Java
- jOptionPane with Custom image icon dialog
- jOptionPane Yes/No option with image dialog
- jOptionPane Error Message dialog
- jOptionPane Information Message dialog
So, let’s find step by step every message process.
Now first we learn how to show simple MsgBox dialog.
First, we drag a jButton for every MsgBox. And after that we will write code inside it, then see what happen in every different jbutton’s ActionPerformed event’s process.
(1). Show simple Plain MessageBox in Java
For showing this dialog, you have to simply import its class. Then call it in any component or run time process.
import javax.swing.JOptionPane;
If there is only simple Msg dialog requirement, this is called plain MsgBox. We want to show it through butons’s click activity. So, type following code as we written.
private void MsgBtnActionPerformed(java.awt.event.ActionEvent evt) { JOptionPane.showMessageDialog(null, "Basic Plain Msg", "Plain MsgBox", JOptionPane.PLAIN_MESSAGE); }
When you run it, it will show the following output.
![]() |
| Plain Msg dialogbox |
(2). jOptionPane with Custom image icon dialog
Suppose you have an image icon, which you want to show with containing message box, which indicate your application process. Then create an image icon and save it as .png or .jpg format and drag it to your package.
Suppose we have a file with name «msgicon.png»
. Then write code like:
private void ImgMsgBtnActionPerformed(java.awt.event.ActionEvent evt) { try{ BufferedImage imageicn1 = ImageIO.read(getClass().getResource("msgicon.png")); ImageIcon iconsk = new ImageIcon(imageicn1); JOptionPane.showConfirmDialog(null, "Custome Image Base Msg", "Msg with Image icon", JOptionPane.PLAIN_MESSAGE, 3, iconsk); }catch(Exception msex1){} }
After that this code will present a custom icon base msg.
![]() |
| Custom Image Base Msg DialogBox |
SQL Server Database Connectivity in Netbeans with Easy Tech Tips
(3). jOptionPane Yes/No option with image dialog :
For saving or editing or some other action you need a MsgBox that show Yes/No option for that process. You have to add if else statement for it.
For clear description we add some jLabel and will see the output of Yes/No button press, which show in jLabel.
For more understanding purpose, just look at following code:
private void YesNoMsgBtnActionPerformed(java.awt.event.ActionEvent evt) { try{ BufferedImage imageicn1 = ImageIO.read(getClass().getResource("msgicon.png")); ImageIcon iconsk = new ImageIcon(imageicn1); //Condition if you press "Yess" Button. if (JOptionPane.showConfirmDialog(null, "Sure for this process", "Ye No Option", JOptionPane.YES_NO_OPTION,3, iconsk) == JOptionPane.YES_OPTION) { jLabel2.setText("Yes"); jLabel2.setForeground(Color.blue); } //Otherwise if you press “No” Button. else { jLabel2.setText("No"); jLabel2.setForeground(Color.red); } }catch(Exception msgl){} }
And run-time this will show like:
![]() |
| Yes/No Msg Dialog |
As you can see when pressing on “Yes” button, the result is showing in jLabel2 as “Yes” and pressing on “No” button, the result is showing in jLabel2 as “No”.
jList to Display data or Items in Java Swing
(4). jOptionPane Error Message dialog :
If you want to show an error Msgbox, there is simple code for it.
private void ErrMsgBtnActionPerformed(java.awt.event.ActionEvent evt) { JOptionPane.showMessageDialog(null, "Sorry Activity Fail", "Activity Fail Error" , JOptionPane.ERROR_MESSAGE); }
![]() |
| Error Dialog Box |
(5). jOptionPane Information Message dialog :
For successful saving, editing, deleting and listing information, you need to show the information MsgBox. Just change some code inside error dialog. And the Msg dialog will be change in information dialog.
private void InfoMsgBtnActionPerformed(java.awt.event.ActionEvent evt) { JOptionPane.showMessageDialog(null, "Successfully Done Activity", "Activity Done Information" , JOptionPane.INFORMATION_MESSAGE); }
![]() |
| Information Dialog Box |
So, there is some Types and Use of JOptionPane in Java Swing for Messages in NetBeans as described above with step by step process, just do same as SKOTechLearn Tips mention above.
- Tweet
- Share
- Share
- Share
Introduction
The class JOptionPane is a component which provides standard methods to pop up a standard dialog box for a value or informs the user of something.
Class Declaration
Following is the declaration for javax.swing.JOptionPane class −
public class JOptionPane
extends JComponent
implements Accessible
Field
Following are the fields for javax.swing.JOptionPane class −
-
static int CANCEL_OPTION − Return value from class method if CANCEL is chosen.
-
static int CLOSED_OPTION − Return value from class method if the user closes window without selecting anything, more than likely this should be treated as either a CANCEL_OPTION or NO_OPTION.
-
static int DEFAULT_OPTION − Type meaning Look and Feel should not supply any options only use the options from the JOptionPane.
-
static int ERROR_MESSAGE − Used for error messages.
-
protected Icon icon − Icon used in pane.
-
static string ICON_PROPERTY − Bound property name for icon.
-
static int INFORMATION_MESSAGE − Used for information messages.
-
static string INITIAL_SELECTION_VALUE_PROPERTY − Bound property name for initialSelectionValue.
-
static string INITIAL_VALUE_PROPERTY − Bound property name for initialValue.
-
protected Object initialSelectionValue − Initial value to select in selectionValues.
-
protected Object initialValue − Value that should be initially selected in options.
-
static string INPUT_VALUE_PROPERTY − Bound property name for inputValue.
-
protected Object inputValue − Value the user has input.
-
protected Object message − Message to display.
-
static string MESSAGE_PROPERTY − Bound property name for message.
-
static string MESSAGE_TYPE_PROPERTY − Bound property name for type.
-
static int OK_CANCEL_OPTION − Type used for showConfirmDialog.
-
protected int messageType − Message type.
-
static int NO_OPTION − Return value from class method if NO is chosen.
-
static int OK_OPTION − Return value from class method if OK is chosen.
-
static string OPTION_TYPE_PROPERTY − Bound property name for optionType.
-
protected Object[] options − Options to display to the user.
-
static string OPTIONS_PROPERTY − Bound property name for option.
-
protected int optionType − Option type, one of DEFAULT_OPTION, YES_NO_OPTION, YES_NO_CANCEL_OPTION or OK_CANCEL_OPTION.
-
static int PLAIN_MESSAGE − No icon is used.
-
static int QUESTION_MESSAGE − Used for questions.
-
static string SELECTION_VALUES_PROPERTY − Bound property name for selectionValues.
-
protected Object[] selectionValues − Array of values the user can choose from.
-
static Object UNINITIALIZED_VALUE − Indicates that the user has not yet selected a value.
-
protected Object value − Currently selected value, will be a valid option, or UNINITIALIZED_VALUE or null.
-
static string VALUE_PROPERTY − Bound property name for value.
-
static string WANTS_INPUT_PROPERTY − Bound property name for wantsInput.
-
protected boolean wantsInput − If true, a UI widget will be provided to the user to get input.
-
static int WARNING_MESSAGE − Used for warning messages.
-
static int YES_NO_CANCEL_OPTION − Type used for showConfirmDialog.
-
static int YES_NO_OPTION − Type used for showConfirmDialog.
-
static int YES_OPTION − Return value from class method, if YES is chosen.
Class Constructors
| Sr.No. | Constructor & Description |
|---|---|
| 1 |
JOptionPane() Creates a JOptionPane with a test message. |
| 2 |
JOptionPane(Object message) Creates a instance of JOptionPane to display a message using the plain-message message type and the default options delivered by the UI. |
| 3 |
JOptionPane(Object message, int messageType) Creates an instance of JOptionPane to display a message with the specified message type and the default options |
| 4 |
JOptionPane(Object message, int messageType, int optionType) Creates an instance of JOptionPane to display a message with the specified message type and options. |
| 5 |
JOptionPane(Object message, int messageType, int optionType, Icon icon) Creates an instance of JOptionPane to display a message with the specified message type, options, and icon. |
| 6 |
JOptionPane(Object message, int messageType, int optionType, Icon icon, Object[] options) Creates an instance of JOptionPane to display a message with the specified message type, icon, and options. |
| 7 |
JOptionPane(Object message, int messageType, int optionType, Icon icon, Object[] options, Object initialValue) Creates an instance of JOptionPane to display a message with the specified message type, icon, and options, with the initially-selected option specified. |
Class Methods
| Sr.No. | Method & Description |
|---|---|
| 1 |
JDialog createDialog(Component parentComponent, String title) Creates and returns a new JDialog wrapping this centered on the parentComponent in the parentComponent’s frame. |
| 2 |
JDialog createDialog(String title) Creates and returns a new parentless JDialog with the specified title. |
| 3 |
JInternalFrame createInternalFrame(Component parentComponent, String title) Creates and returns an instance of JInternalFrame. |
| 4 |
AccessibleContext getAccessibleContext() Returns the AccessibleContext associated with this JOptionPane. |
| 5 |
static JDesktopPane getDesktopPaneForComponent(Component parentComponent) Returns the specified component’s desktop pane. |
| 6 |
static Frame getFrameForComponent(Component parentComponent) Returns the specified component’s Frame. |
| 7 |
Icon getIcon() Returns the icon this pane displays. |
| 8 |
Object getInitialSelectionValue() Returns the input value that is displayed as initially selected to the user. |
| 9 |
Object getInitialValue() Returns the initial value. |
| 10 |
Object getInputValue() Returns the value the user has input, if wantsInput is true. |
| 11 |
int getMaxCharactersPerLineCount() Returns the maximum number of characters to place on a line in a message. |
| 12 |
Object getMessage() Returns the message-object this pane displays. |
| 13 |
int getMessageType() Returns the message type. |
| 14 |
Object[] getOptions() Returns the choices the user can make. |
| 15 |
int getOptionType() Returns the type of options that are displayed. |
| 16 |
static Frame getRootFrame() Returns the Frame to use for the class methods in which a frame is not provided. |
| 17 |
Object[] getSelectionValues() Returns the input selection values. |
| 18 |
OptionPaneUI getUI() Returns the UI object which implements the L&F for this component. |
| 19 |
String getUIClassID() Returns the name of the UI class that implements the L&F for this component. |
| 20 |
Object getValue() Returns the value the user has selected. |
| 21 |
boolean getWantsInput() Returns the value of the wantsInput property. |
| 22 |
protected String paramString() Returns a string representation of this JOptionPane. |
| 23 |
void selectInitialValue() Requests that the initial value be selected, which will set focus to the initial value. |
| 24 |
void setIcon(Icon newIcon) Sets the icon to display. |
| 25 |
void setInitialSelectionValue(Object newValue) Sets the input value that is initially displayed as selected by the user. |
| 26 |
void setInitialValue(Object newInitialValue) Sets the initial value that is to be enabled — the Component that has the focus when the pane is initially displayed. |
| 27 |
void setInputValue(Object newValue) Sets the input value that was selected or input by the user. |
| 28 |
void setMessage(Object newMessage) Sets the option pane’s message-object. |
| 29 |
void setMessageType(int newType) Sets the option pane’s message type. |
| 30 |
void setOptions(Object[] newOptions) Sets the options this pane displays. |
| 31 |
void setOptionType(int newType) Sets the options to display. |
| 32 |
static voidsetRootFrame(Frame newRootFrame) Sets the frame to use for class methods in which a frame is not provided. |
| 33 |
void setSelectionValues(Object[] newValues) Sets the input selection values for a pane that provides the user with a list of items to choose from. |
| 34 |
void setUI(OptionPaneUI ui) Sets the UI object which implements the L&F for this component. |
| 35 |
void setValue(Object newValue) Sets the value the user has chosen. |
| 36 |
void setWantsInput(boolean newValue) Sets the wantsInput property. |
| 37 |
static int showConfirmDialog(Component parentComponent, Object message) Brings up a dialog with the options Yes, No and Cancel; with the title, Select an Option. |
| 38 |
static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType) Brings up a dialog where the number of choices is determined by the optionType parameter. |
| 39 |
static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType, int messageType) Brings up a dialog where the number of choices is determined by the optionType parameter, where the messageType parameter determines the icon to display. |
| 40 |
static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType, int messageType, Icon icon) Brings up a dialog with a specified icon, where the number of choices is determined by the optionType parameter. |
| 41 |
static String showInputDialog(Component parentComponent, Object message) Shows a question-message dialog requesting input from the user parented to parentComponent. |
| 42 |
static String showInputDialog(Component parentComponent, Object message, Object initialSelectionValue) Shows a question-message dialog requesting input from the user and parented to parentComponent. |
| 43 |
static String showInputDialog(Component parentComponent, Object message, String title, int essageType) Shows a dialog requesting input from the user parented to parentComponent with the dialog having the title title and message type messageType. |
| 44 |
static Object showInputDialog(Component parentComponent, Object message, String title, int messageType, Icon icon, Object[] selectionValues, Object initialSelectionValue) Prompts the user for input in a blocking dialog where the initial selection, possible selections, and all other options can be specified. |
| 45 |
static String showInputDialog(Object message) Shows a question-message dialog requesting input from the user. |
| 46 |
static String showInputDialog(Object message, Object initialSelectionValue) Shows a question-message dialog requesting input from the user, with the input value initialized to initialSelectionValue. |
| 47 |
static int showInternalConfirmDialog(Component parentComponent, Object message) Brings up an internal dialog panel with the options Yes, No and Cancel; with the title, Select an Option. |
| 48 |
static int showInternalConfirmDialog(Component parentComponent, Object message, String title, int optionType) Brings up a internal dialog panel where the number of choices is determined by the optionType parameter. |
| 49 |
static int showInternalConfirmDialog(Component parentComponent, Object message, String title, int optionType, int messageType) Brings up an internal dialog panel where the number of choices is determined by the optionType parameter, where the messageType parameter determines the icon to display. |
| 50 |
static int showInternalConfirmDialog(Component parentComponent, Object message, String title, int optionType, int messageType, Icon icon) Brings up an internal dialog panel with a specified icon, where the number of choices is determined by the optionType parameter. |
| 51 |
static String showInternalInputDialog(Component parentComponent, Object message) Shows an internal question-message dialog requesting input from the user parented to parentComponent. |
| 52 |
static String showInternalInputDialog(Component parentComponent, Object message, String title, int messageType) Shows an internal dialog requesting input from the user parented to parentComponent with the dialog having the title title and message type messageType. |
| 53 |
static Object showInternalInputDialog(Component parentComponent, Object message, String title, int messageType, Icon icon, Object[] selectionValues, Object initialSelectionValue) Prompts the user for input in a blocking internal dialog where the initial selection, possible selections, and all other options can be specified. |
| 54 |
static voidshowInternalMessageDialog(Component parentComponent, Object message) Brings up an internal confirmation dialog panel. |
| 55 |
static voidshowInternalMessageDialog(Component parentComponent, Object message, String title, int messageType) Brings up an internal dialog panel that displays a message using a default icon determined by the messageType parameter. |
| 56 |
static voidshowInternalMessageDialog(Component parentComponent, Object message, String title, int messageType, Icon icon) Brings up an internal dialog panel displaying a message, specifying all parameters. |
| 57 |
static voidshowMessageDialog(Component parentComponent, Object message) Brings up an information-message dialog titled «Message». |
| 58 |
static voidshowMessageDialog(Component parentComponent, Object message, String title, int messageType) Brings up a dialog that displays a message using a default icon determined by the messageType parameter. |
| 59 |
static voidshowMessageDialog(Component parentComponent, Object message, String title, int messageType, Icon icon) Brings up a dialog displaying a message, specifying all parameters. |
| 60 |
static int showOptionDialog(Component parentComponent, Object message, String title, int optionType, int messageType, Icon icon, Object[] options, Object initialValue) Brings up a dialog with a specified icon, where the initial choice is determined by the initialValue parameter and the number of choices is determined by the optionType parameter. |
| 61 |
void updateUI() Notification from the UIManager that the L&F has changed. |
| 62 |
static int showInternalOptionDialog(Component parentComponent, Object message, String title, int optionType, int messageType, Icon icon, Object[] options, Object initialValue) Brings up an internal dialog panel with a specified icon, where the initial choice is determined by the initialValue parameter and the number of choices is determined by the optionType parameter. |
Methods Inherited
This class inherits methods from the following classes −
- javax.swing.JComponent
- java.awt.Container
- java.awt.Component
- java.lang.Object
JOptionPane Example
Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingControlDemo.java
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingControlDemo {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public SwingControlDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingControlDemo swingControlDemo = new SwingControlDemo();
swingControlDemo.showDialogDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java Swing Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showDialogDemo(){
headerLabel.setText("Control in action: JOptionPane");
JButton okButton = new JButton("OK");
JButton javaButton = new JButton("Yes/No");
JButton cancelButton = new JButton("Yes/No/Cancel");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(mainFrame, "Welcome to TutorialsPoint.com");
}
});
javaButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int output = JOptionPane.showConfirmDialog(mainFrame
, "Click any button"
,"TutorialsPoint.com"
,JOptionPane.YES_NO_OPTION);
if(output == JOptionPane.YES_OPTION){
statusLabel.setText("Yes selected.");
} else if(output == JOptionPane.NO_OPTION){
statusLabel.setText("No selected.");
}
}
});
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int output = JOptionPane.showConfirmDialog(mainFrame
, "Click any button"
,"TutorialsPoint.com"
,JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.INFORMATION_MESSAGE);
if(output == JOptionPane.YES_OPTION){
statusLabel.setText("Yes selected.");
} else if(output == JOptionPane.NO_OPTION){
statusLabel.setText("No selected.");
} else if(output == JOptionPane.CANCEL_OPTION){
statusLabel.setText("Cancel selected.");
}
}
});
controlPanel.add(okButton);
controlPanel.add(javaButton);
controlPanel.add(cancelButton);
mainFrame.setVisible(true);
}
}
Compile the program using the command prompt. Go to D:/ > SWING and type the following command.
D:SWING>javac comtutorialspointguiSwingControlDemo.java
If no error occurs, it means the compilation is successful. Run the program using the following command.
D:SWING>java com.tutorialspoint.gui.SwingControlDemo
Verify the following output.

swing_controls.htm




