javaswingjtextfieldkeylistener

KeyListener not responding after value modification in JTextField


I'm writing a program in java that opens a window and detects keystrokes.

However, there is one fatal problem. if i modify the value in TextField, KeyListener will not work again. Here is the code that summarizes the problem situation I ran into:

    
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class Main extends JFrame {
    private Main(){

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
        setSize(500,500);
        setPreferredSize(new Dimension(500,500));

        JPanel textFieldPanel = new JPanel();
        textFieldPanel.setFocusable(true);
        textFieldPanel.setLayout(new BorderLayout());
        JTextField textField = new JTextField();
        textField.setFocusable(true);
        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) { //it is not responding after value modification in JTextField...
                System.out.println("test");
            }
        });
        textFieldPanel.add(textField);
        add(textFieldPanel);

        pack();
    }
    public static void main(String[] args) {
        new Main();
    }
}

I want to make it get a KeyListener even while entering a value, And also want to know why the listener is disabled.

I've disabled the fields via the disable and re-enable method, but the KeyListener still doesn't work.

        textField.addActionListener(e -> {
            textField.setEnabled(false);
            textField.setEnabled(true);
        });

How can I make it want to receive only the shortcuts, without the help of any external classes? Since I added it directly to the JFrame, it doesn't seem to be a focusing issue.


Solution

  • In order for your Listener to be applicable to your textField, you need to change this:

    addKeyListener(new KeyAdapter() {
                @Override
                public void keyPressed(KeyEvent e) { //it is not responding after value modification in JTextField...
                    System.out.println("test");
                }
            });
    

    into this:

    textField.addKeyListener(new KeyAdapter() {
                @Override
                public void keyPressed(KeyEvent e) { //it is not responding after value modification in JTextField...
                    System.out.println("test");
                }
            });
    

    At current, your Listener is attached to your Frame, which is completely covered by the textField.