Java swing сообщение об ошибке

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

120k97 gold badges307 silver badges386 bronze badges

asked Jun 7, 2011 at 19:10

Oleg Vazhnev's user avatar

Oleg VazhnevOleg Vazhnev

23.1k54 gold badges170 silver badges304 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,4801 gold badge13 silver badges21 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.7k28 gold badges132 silver badges188 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

8142 gold badges11 silver badges22 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

Show a error message alert

swingexamples_dialogs.htm

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.

Окно сообщения в Java

Окно сообщения в 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, диалоговое окно с предупреждением будет выглядеть, как показано ниже.

Всплывающее диалоговое окно с предупреждением

Есть еще несколько типов сообщений, которые можно использовать при необходимости.

Возможно, вам также будет интересно:

  • Java net sockettimeoutexception read timed out ошибка
  • Java net socketexception network is unreachable как исправить ошибку
  • Java lang unsupportedoperationexception ошибка
  • Java lang securityexception ошибка как исправить на андроид
  • Java lang runtimeexception ошибка андроид

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии