How to fixed keylistener on JTextField?

梦想的初衷 提交于 2019-11-28 02:26:16

The short answer is don't. Use a DocumentFilter to change what gets entered into a JTextComponent or a DocumentListener if you want to know when the content of the field changes.

KeyListener will not take into account what happens if the user pastes text into the field or if the field is modified programmatically

See DocumentFilter Examples and Implementing a Document Filter and Listening for Changes on a Document for more details

If your bar code scanner is injecting key events into the event queue, you may wish to inject an artificial delay into the DocumentFilter, as you won't want to process the field until AFTER all the key strokes are entered.

For example...

This basically uses a Swing Timer set to short delay (250 milliseconds in this case), each time the field is updated (and the DocumentListener is notified), it restarts the Timer. This means there must be delay of at least 250 milliseconds from the last update before the Timer can trigger the registered ActionListener and update the label.

public class TestPane extends JPanel {

    private Timer updateTimer;
    private JTextField field;
    private JLabel label;

    public TestPane() {
        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = GridBagConstraints.REMAINDER;

        updateTimer = new Timer(250, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                label.setText(field.getText());
            }
        });
        updateTimer.setRepeats(false);

        label = new JLabel("...");
        field = new JTextField(14);
        field.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void insertUpdate(DocumentEvent e) {
                processUpdate();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                processUpdate();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                processUpdate();
            }

        });

        add(field, gbc);
        add(label, gbc);
    }

    protected void processUpdate() {
        updateTimer.restart();
    }

}

You might like to play around with the delay a little.

The bar code scanner may also be inserting a Enter key into the event queue, so it might be worth testing the field by registering an ActionListener against it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!