Java dialog error message

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.

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's user avatar

Jonas

117k96 gold badges305 silver badges381 bronze badges

asked Jun 7, 2011 at 19:10

Oleg Vazhnev's user avatar

Oleg VazhnevOleg Vazhnev

22.9k54 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

Jonas's user avatar

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 Erraoudy's user avatar

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

Heisenbug's user avatar

HeisenbugHeisenbug

38.5k28 gold badges133 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 Dias's user avatar

Ramon DiasRamon Dias

7042 gold badges9 silver badges20 bronze badges

3

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's user avatar

Jonas

117k96 gold badges305 silver badges381 bronze badges

asked Jun 7, 2011 at 19:10

Oleg Vazhnev's user avatar

Oleg VazhnevOleg Vazhnev

22.9k54 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

Jonas's user avatar

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 Erraoudy's user avatar

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

Heisenbug's user avatar

HeisenbugHeisenbug

38.5k28 gold badges133 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 Dias's user avatar

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 Кб).

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:

  1. Show simple Plain MessageBox in Java
  2. jOptionPane with Custom image icon dialog
  3. jOptionPane Yes/No option with image dialog
  4. jOptionPane Error Message dialog
  5. 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 Message box in Netbeans
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» Message Icon in java. 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 Message box in Netbeans
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:

YesNoOption Msg Box in Netbeans
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 Msg dialog in Netbeans
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 Message box in java
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

Any type of Graphical User Interface (GUI) application, designed based on any functional requirement, will assume user interaction as part of its standard functionality. Therefore, almost all GUIs allow users to enter data and manipulate it. After the information is gathered from the user, it typically needs to be either stored, locally or remotely, or used in the application in real time. But, before doing something with the data, applications usually need to check it for correctness. In this article, I will concentrate on form validation and dynamic creation of notification messages in Java Swing GUI applications. I will also go over a few useful tips for GUI developers such as adding listeners to multiple components and using regular expressions for easy validations.

Because Java/J2EE became de facto for enterprise rapid development and deployment environments, especially in the financial industry, the Java Swing framework became a favorite choice for desktop applications as well. With Swing, programmers can create extremely robust GUI applications in a short period of time and deploy them on any platform, without recompilation or any other changes for that matter. The applications will behave exactly the same on multiple platforms, and the only downside will be a need to have the Java Runtime Environment (JRE) installed on the target machines.

User Form

To demonstrate user form validation, I created a small application based on fictional requirements that entail a user entry screen that gathers rudimentary information, such as first and last name, and machine IP address. A form with several text fields takes user data and, after checking it, allows the user to proceed.

The fictional requirements also say that user may want to press the “Enter” key after entering data in any field to proceed, in addition to being able to click on the “Next” button. Moreover, the IP address needs to be checked for correct format (IPv4).

Dynamic Validation

Although the basics of creating the Swing GUI is beyond the scope of this article, you should be familiar with creating simple interfaces, using any layout manager either manually or with an IDE. For this article, I have used JBuilderX to create a frame with GridBagLayout and add all the required components. The form in the sample application is trivial because it contains only a few labels and text fields. Nevertheless, validation needs to be done on every component and the technique to do it can be applied to any GUI, no matter how complex. For instance, all fields need to be filled before the user can proceed and the IP field needs to have an additional check for the correct format.

The simplest way to check fields would be to add an action that listens to the “NEXT” button, and when a new action event is fired (on button press), check every field one by one for correctness and display an error message if something is wrong.

Ex. method checkFields () {    // pseudo code
   if (field1 is not right)
   show error
   if (field2 is not right)
   show new error
   ... etc ...
}

The problem with this approach is that when multiple fields are incorrect, the user would see a lot of error massages at the same time—several pop-ups, for instance. Another problem is that every field needs to have its own code to show the error message. Therefore, if the logic to display errors is not as simple as printing out to an output stream somewhere, it would have to be redundantly used to display every error statement.

In this case, the requirement is to show a pop-up dialog such as JOptionPane.showMessageDialog.

The solution to having multiple dialogs pop up at the same time could be breaking out of the check method after the first error was found, but this still does not solve the redundancy of implementing and showing a new dialog for every error condition. Redundancy can become abundant if the GUI is very complex.

So, what is the graceful solution?

An important, not well known, property of Java dialogs is that they can take an array of an object as a parameter to display multi-line messages. For example:

JOptionPane.showMessageDialog(this, new String[]{"Hello", "World"});

You can even pass in objects with different text properties color, font, and so forth. The solution, therefore, is to display only one dialog at the end of the validation routine and pass in an array of error messages. The array would be dynamically created based on errors found and the user would see all of them in one pop-up.

In the case of my simple application, the code looks like this; a new array list is initialized and, on every error condition, a string message is added to it. At the end, if array is empty, nothing is displayed; if it’s not empty, it is passed to the dialog as a parameter, and a dynamic pop-up is shown.

private boolean checkFields() {
   // init array
   ArrayList msg = new ArrayList(0);
   // check if first name is blank
   if (getRoleNameTF().getText() == null ||
      getRoleNameTF().getText().equals("")) {
      msg.add("Please enter First Name Field - it is required!");
   }
   // check if last name is blank
   if (getRoleURNTF().getText() == null ||
      getRoleURNTF().getText().equals("")) {
      msg.add("Please enter Last Name Field - it is required!");
   }
   // check if ip is blank
   if (getRoleIPTF().getText() == null ||
      getRoleIPTF().getText().equals("")) {
      msg.add("Please check IP Field - format ###.###.###.###");
   // check if ip is correct format
   else if (!getRoleIPTF().getText().matches(
         "([d]{1,3}.){3}[d]{1,3}")) {
      msg.add("IP Field Incorrect - format ###.###.###.###");
   }
   // dynamic dialog
   if (!msg.isEmpty()) {
      JOptionPane.showMessageDialog(this, msg.toArray());
      return false;
   }
   return true;
}

public void actionPerformed(ActionEvent e) {
   if (checkFields()){
      // all ok do something
      JOptionPane.showMessageDialog(this, "All fields are ok!");
      parent.next();
   }
}

Note the IP is also checked for correctness with a regular expression. Because the message is dynamic, it will be different depending on the errors found:

Implementing this technique solved both problems of multi pop-ups and code reuse, and it can be applied to GUIs of any complexity and size. The resulting array of error massages can be passed or used in any context and not necessarily in JDialogs.

Adding Multiple Action Listeners

The validation was initialized when the user clicks on the “NEXT” button because it has an action listener associated with it. If the requirements say that the user needs to be able to simply press the Enter key while the focus is on any field, we need to add a key listener to every single text field. This would require adding some Key adapter or implementing a key listener interface and then checking whether the key pressed was indeed an “Enter” key. Besides, every text filed also would need to register to generate key events. Luckily, there is another way.

Java 2 provides an extremely useful feature built in specifically for capturing an Enter key press on the text fields. Simply attaching an action listener to any text field component would generate an action event if Enter was pressed on it. However, this still necessitates explicitly attaching an action listener to every field.

To solve this, I interrogated the parent component panel for the list of all text fields added to it and, as I traversed through them, I attached the listeners dynamically.

Component fields[] = this.getComponents();
   for (int i = 0; i < fields.length; i++) {
      if (fields[i] instanceof JTextField) {
         ((JTextField) fields[i]).addActionListener(this);
      }
   }

This method can also be used to add any kind of listeners to GUIs of any complexity—because you can recursively navigate down if the component in scope is in another container.

For instance, passing a top parent GUI container to this method will recursively add action listeners to all text fields, even those that are added to the child containers.

public void attachAnyListener(JComponent component){
   Component fields[] = component.getComponents();
      for (int i = 0; i < fields.length; i++) {
         if (fields[i] instanceof JComponent) {
            attachAnyListener(fields[i]);
         }
         if (fields[i] instanceof JTextField) {
               ((JTextField) fields[i]).addActionListener(this);
            }
         //other listener attachments here
      }
}

Note: The recursive mechanism also can be used to detect any changes to the user-entered information in large GUIs by using focus listeners or change listeners. Eventually, you prompt the user whether changes need to be saved on exit.

After attaching action listeners to the text fields, the application will start checking all fields. It doesn’t just check the “NEXT” button press; it also checks on an “Enter” key press on any text field by calling checkFields() in the actionPerformed method.

The last validation check was for the IP address format. I used a regular expression feature available in the matches() String class method. The field is checked by a pattern of the simple IPv4 format that can be only 1 to 3 digits followed by a period, repeating 3 times, and followed by another set of 1 to 3 digits.

matches("([d]{1,3}.){3}[d]{1,3}"))

The regular expressions (regex) are built into Java and even have a separate package in JDK java.util.regex. The Sting class uses pattern matching capabilities of regular expressions in several methods (please see the JDK API documentation for more information). The regex are very powerful and can allow for very complex matching, such as «^(([^:/?#]+):)?((//([^/?#]*))?([^?#]*)(?([^#]*))?)?(#(.*))?» or something even worse looking.

Conclusion

In this article, I’ve shown how to dynamically generate notification/validation messages. The technique can be applied to any GUI developed in Swing. I have also described how to add action listeners to any component implicitly and validate data using regular expressions. Even though the validation and notification is specific to the Java Swing toolkit, the technique can be applied to the most modern GUI toolkits.

Download the Code

You can download the source code used in this article here.

References

Java Swing, 2nd Edition by Marc Loy, Robert Eckstein, Dave Wood, James Elliott, and Brian Cole. November 2002. ISBN: 0-596-00408-7.

The Java Developers Almanac 1.4: http://javaalmanac.com/egs/java.util.regex/pkg.html

About the Author

Vlad Kofman is a System Architect working on projects under government defense contracts. He has also been involved with enterprise-level projects for major Wall Street firms and the U.S. government. His main interests are object-oriented programming methodologies and design patterns.

Понравилась статья? Поделить с друзьями:
  • J338 ошибка ауди
  • J2534 read error 16
  • J2534 config app error reading version information
  • J1850 ошибка ниссан
  • J0511 kyocera ошибка