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