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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…