Рина Сергеева
Рина Сергеева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
AD

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10
Last comments
Evgenii Legotckoi
Evgenii LegotckoiOct. 31, 2024, 2:37 p.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 8:19 a.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 7:51 a.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 11:02 a.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
k
kmssrFeb. 8, 2024, 6:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Now discuss on the forum
Evgenii Legotckoi
Evgenii LegotckoiJune 24, 2024, 3:11 p.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
t
tonypeachey1Nov. 15, 2024, 6:04 a.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
NSProject
NSProjectJune 4, 2022, 3:49 a.m.
Всё ещё разбираюсь с кешем. В следствии прочтения данной статьи. Я принял для себя решение сделать кеширование свойств менеджера модели LikeDislike. И так как установка evileg_core для меня не была возможна, ибо он писался…
9
9AnonimOct. 25, 2024, 9:10 a.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks