It should work analog to the Java Swing solution presented here.
I assume the final character coming from the barcode scanner is ENTER. If not, you must check how to know when the barcode is done, e.g. by the expected length or by testing for summed up time between the key events or whatever.
The KeyEvents from your barcode scanner should come fast, so the time between two events should be rather short. To filter out manual typing, the StringBuffer is reset if events come too slow.
In your KeyListener, you can now implement this method:
private final StringBuffer barcode = new StringBuffer();
private long lastEventTimeStamp = 0L;
// ...
public void keyTyped(KeyEvent keyEvent) {
long now = Instant.now().toEpochMilli();
// events must come fast enough to separate from manual input
if (now - this.lastEventTimeStamp > this.threshold) {
barcode.delete(0, barcode.length());
}
this.lastEventTimeStamp = now;
// ENTER comes as 0x000d
if (keyEvent.getCharacter().charAt(0) == (char) 0x000d) {
if (barcode.length() >= this.minBarcodeLength) {
System.out.println("barcode: " + barcode);
}
barcode.delete(0, barcode.length());
} else {
barcode.append(keyEvent.getCharacter());
}
keyEvent.consume();
}
This is just a rough implementation which probably requires some fine tuning, but I've tested it in an FXML controller for a GridPane and for the barcode scanner I have it works.
Note: The KeyEvent.KEY_TYPED does not have the KeyCode set, so you cannot do this:
if (event.getCode().equals(KeyCode.ENTER)) {
//...
}