Рина Сергеева
May 3, 2018, 1:04 p.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

  1. JTextField textField = new JTextField();

place it on the panel or frame

  1. 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;

  1. numberOfRouteTextField.addKeyListener(new KeyListener() {
  2.  
  3. public void keyPressed(KeyEvent event) {
  4. ... ... ...
  5. }
  6. public void keyReleased(KeyEvent event) {
  7. ... ... ...
  8. }
  9. public void keyTyped(KeyEvent event) {
  10. ... ... ...
  11. }
  12. });

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

  1. numberOfRouteTextField.addKeyListener(new NumberKeyListener());
  2.  
  3. class NumberKeyListener extends KeyAdapter {
  4. public void keyReleased(KeyEvent e) {
  5. ... ... ...
  6. }
  7. }

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:

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

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.

  1. import javax.swing.*;
  2. import javax.swing.table.DefaultTableModel;
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. import java.util.ArrayList;
  6.  
  7. public class Routes {
  8.  
  9. private JTextField numberOfRouteTextField;
  10. private DefaultTableModel tableModel;
  11. private Frame frame;
  12. private ArrayList<String[]> dataOfTableAboutRoutes;
  13.  
  14. public static void main(String args[]) {
  15.  
  16. Routes routes = new Routes();
  17. routes.CreateGui();
  18. }
  19.  
  20. private void CreateGui() {
  21.  
  22. frame = new JFrame("Building a route table");
  23. JLabel numberOfRoutesLabel;
  24. JPanel widgetPanel = new JPanel(); // create a panel where all the elements will be located
  25. GridBagLayout gblWidgetPanel = new GridBagLayout(); // define the layout manager
  26. GridBagConstraints constraints = new GridBagConstraints();
  27. widgetPanel.setLayout(gblWidgetPanel);
  28.  
  29. numberOfRoutesLabel = new JLabel("Number of routes:");
  30. constraints.gridwidth = 1; // how many cells the object occupies
  31. constraints.gridy = 0; // which vertical cell counts
  32. gblWidgetPanel.setConstraints(numberOfRoutesLabel, constraints);
  33. widgetPanel.add(numberOfRoutesLabel);
  34.  
  35. numberOfRouteTextField = new JTextField(10);
  36. constraints.gridy = 1;
  37. numberOfRouteTextField.addKeyListener(new NumberKeyListener()); // add the listener to the TextField
  38. gblWidgetPanel.setConstraints(numberOfRouteTextField, constraints);
  39. widgetPanel.add(numberOfRouteTextField); // place on the panel
  40.  
  41. dataOfTableAboutRoutes = new ArrayList<>(); // here all the contents of the table will be stored
  42. tableModel = new DefaultTableModel();
  43. JTable writingRoutesTable = new JTable(tableModel);
  44. constraints.gridy = 2; // how many cells does the table occupy
  45. gblWidgetPanel.setConstraints(writingRoutesTable, constraints);
  46. widgetPanel.add(writingRoutesTable);
  47.  
  48. frame.add(BorderLayout.WEST,widgetPanel);
  49. frame.setSize(300, 300);
  50. frame.setVisible(true);
  51. }
  52.  
  53. class NumberKeyListener extends KeyAdapter { // extend the abstract class of KeyAdapter
  54.  
  55. public void keyReleased(KeyEvent event) { // redefine necessary methods
  56.  
  57. // This method will work after the user enters any character from the keyboard
  58. // it would be nice to do a check on the input data, so that it's only integers
  59.  
  60. if (event.getKeyCode() != KeyEvent.VK_BACK_SPACE) {
  61.  
  62. // If the user pressed BackSpace with the desire to erase the contents, the body of the function will not be executed
  63.  
  64. String[] columnNames = new String[]{"Route number", "Start", "Finish"}; // set table headers
  65. int numberOfRoutes = Integer.parseInt(numberOfRouteTextField.getText()); // get the number from TextField
  66.  
  67. for (int i = 0; i < dataOfTableAboutRoutes.size(); i++) {
  68. tableModel.removeRow(0);
  69. // after removal, the elements are shifted, so each time we delete the first element
  70. }
  71. dataOfTableAboutRoutes.clear(); // clear the contents of the table
  72.  
  73. for (int i = 1; i <= numberOfRoutes; i++) {
  74. String[] temp = {"route " + i, "",""};
  75. dataOfTableAboutRoutes.add(temp); // enter the number of rows in the table equal to the given number
  76. }
  77. tableModel.setColumnIdentifiers(columnNames); // set the table headers
  78. for (String[] dataOfTable : dataOfTableAboutRoutes) {
  79. tableModel.addRow(dataOfTable); // put the contents of the ArrayList into the table
  80. }
  81. }
  82. }
  83. }
  84. }

You can see work of program on following images.

By article asked0question(s)

2

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html