Рина Сергеева
Рина СергееваMay 3, 2018, 3:04 a.m.

Handling keyboard events with KeyListener in TextField

Sometimes there is a need to perform certain actions by keys pressing in the TextField . Next, let's see how you can handle events that come from the keyboard.

First we create JTextField

JTextField textField = new JTextField();

place it on the panel or frame

panel.add(textField);

Now you need to add a listener that will be called every time when you type data in TextField. We will use KeyListener interface from the java.awt.event.


The KeyListener interface has 3 methods:

  • void keyPressed (KeyEvent e);

It is called when the user presses any key.

  • void keyReleased (KeyEvent e);

It is called after the user presses and releases any key.

  • void keyTyped (KeyEvent e);

It is activated every time the user type the Unicode characters.

Table of Unicode characters

You can add a listener interface in two ways:

1) implement this interface and all its methods;

numberOfRouteTextField.addKeyListener(new KeyListener() {

    public void keyPressed(KeyEvent event) {
    ... ... ... 
    }
    public void keyReleased(KeyEvent event) {
    ... ... ... 
    }
    public void keyTyped(KeyEvent event) {
    ... ... ... 
    }
});

2) extend the abstract class of KeyAdapter , redefining only the necessary methods.

numberOfRouteTextField.addKeyListener(new NumberKeyListener());

class NumberKeyListener extends KeyAdapter {
    public void keyReleased(KeyEvent e) {
    ... ... ...  
    }
}

Besides, we can make the event called when you press a particular key. Each character, number, letter and control keys on the keyboard have their own code (key code). Add a check in any of the overridden methods. For example, the body of the method will be executed after the user presses the Enter key only:

public void keyReleased(KeyEvent event) {
    if(event.getKeyCode() == KeyEvent.VK_ENTER ) {
    // тело метода
    }
}

Below is an example of a small implementation. What do I want to receive?

I have a TextField field is named numberOfRouteTextField. The user types the number of paths. Then, right after the number is entered, a table with the number of lines equal to the entered number appears.

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;

public class Routes {

    private JTextField numberOfRouteTextField;
    private DefaultTableModel tableModel;
    private Frame frame;
    private ArrayList<String[]> dataOfTableAboutRoutes;

    public static void main(String args[]) {

        Routes routes = new Routes();
        routes.CreateGui();
    }

    private void CreateGui() {

        frame = new JFrame("Building a route table");
        JLabel numberOfRoutesLabel;
        JPanel widgetPanel = new JPanel();                      // create a panel where all the elements will be located
        GridBagLayout gblWidgetPanel = new GridBagLayout();     // define the layout manager
        GridBagConstraints constraints = new GridBagConstraints();
        widgetPanel.setLayout(gblWidgetPanel);

        numberOfRoutesLabel = new JLabel("Number of routes:");
        constraints.gridwidth = 1;   // how many cells the object occupies
        constraints.gridy = 0;       //  which vertical cell counts
        gblWidgetPanel.setConstraints(numberOfRoutesLabel, constraints);
        widgetPanel.add(numberOfRoutesLabel);

        numberOfRouteTextField = new JTextField(10);
        constraints.gridy = 1;
        numberOfRouteTextField.addKeyListener(new NumberKeyListener()); // add the listener to the TextField
        gblWidgetPanel.setConstraints(numberOfRouteTextField, constraints);
        widgetPanel.add(numberOfRouteTextField);           // place on the panel

        dataOfTableAboutRoutes = new ArrayList<>();   // here all the contents of the table will be stored
        tableModel = new DefaultTableModel();
        JTable writingRoutesTable = new JTable(tableModel);
        constraints.gridy = 2;          // how many cells does the table occupy
        gblWidgetPanel.setConstraints(writingRoutesTable, constraints);
        widgetPanel.add(writingRoutesTable);

        frame.add(BorderLayout.WEST,widgetPanel);
        frame.setSize(300, 300);
        frame.setVisible(true);
    }

    class NumberKeyListener extends KeyAdapter {   // extend the abstract class of KeyAdapter

        public void keyReleased(KeyEvent event) {  // redefine necessary methods

            // This method will work after the user enters any character from the keyboard
            // it would be nice to do a check on the input data, so that it's only integers

            if (event.getKeyCode() != KeyEvent.VK_BACK_SPACE) {

                // If the user pressed BackSpace with the desire to erase the contents, the body of the function will not be executed

                String[] columnNames = new String[]{"Route number", "Start", "Finish"}; // set table headers
                int numberOfRoutes = Integer.parseInt(numberOfRouteTextField.getText());  // get the number from TextField

                for (int i = 0; i < dataOfTableAboutRoutes.size(); i++) {
                    tableModel.removeRow(0);
                    // after removal, the elements are shifted, so each time we delete the first element
                }
                dataOfTableAboutRoutes.clear();  // clear the contents of the table

                for (int i = 1; i <= numberOfRoutes; i++) {
                    String[] temp = {"route " + i, "",""};
                    dataOfTableAboutRoutes.add(temp); // enter the number of rows in the table equal to the given number
                }
                tableModel.setColumnIdentifiers(columnNames); // set the table headers
                for (String[] dataOfTable : dataOfTableAboutRoutes) {
                    tableModel.addRow(dataOfTable);    // put the contents of the ArrayList into the table
                }
            }
        }
    }
}

You can see work of program on following images.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
e
  • ehot
  • March 31, 2024, 11:29 a.m.

C++ - Тест 003. Условия и циклы

  • Result:78points,
  • Rating points2
B

C++ - Test 002. Constants

  • Result:16points,
  • Rating points-10
B

C++ - Test 001. The first program and data types

  • Result:46points,
  • Rating points-6
Last comments
k
kmssrFeb. 8, 2024, 3:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 7:30 a.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 5:38 a.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 18, 2023, 6:01 p.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
a
a_vlasovApril 14, 2024, 3:41 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 13, 2024, 11:35 p.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 1:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…
AC
Alexandru CodreanuJan. 19, 2024, 8:57 a.m.
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…

Follow us in social networks