I have created a simple swing app with input text to read the barcode and print the GS character position in output text.
EX:
input : 01070462616434291722010010Y0238921MA3W7J59UC2W111 (get from barcode scanner)
output: GS1 on position = 32
Normal swing app its working properly but when creating a small delay for Key Event processor (add Thread.sleep(2) for each key event )sometimes this output is not there because some other character is generating instead of GS character. ( The reason of adding delay is , in the production code synthetica is used to add look and feel in the swing app and because of that processes there seems some delays for the key events. Therefore in this simple app forcefully add a delay just to simulate the issue. )
Even thought GS is not coming sometimes but the character sequence for the GS character is very same every time
GS character sequence -> ALT + 0 + 0 + 2 + 9
Here the printed Key pressed and release key sequence for GS character (This is just to verify the character sequence when key press and key release and not included in to the recent code )
Key Event | Key Value | Key char |
---|---|---|
Key Pressed | 65535 (ALT key) | |
Key Pressed | 0 | 48 |
Key Released | 0 | 48 |
Key Pressed | 0 | 48 |
Key Released | 0 | 48 |
Key Pressed | 2 | 50 |
Key Released | 2 | 50 |
Key Pressed | 9 | 57 |
Key Released | 65535 (ALT key) | |
Key Typed | 29 |
This is a correct scenario and GS character is typed as expected as in last row (Key char 29 is GS character) , but in incorrect scenario all the other key events are same but key typed character is different
Here is the source code
SwingApp
import java.awt.*;
public class SwingApp {
public static void main(String[] args) {
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventPostProcessor(keyEvent -> {
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
});
EventQueue.invokeLater(() -> new ScannerWindow().show());
}
}
ScannerWindow
import javax.swing.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class ScannerWindow {
private int i;
private final JFrame f;
public ScannerWindow(){
f = new JFrame();
f.setLayout( null);
JTextArea ta = new JTextArea();
JTextField txt=new JTextField();
txt.setBounds(130,20,300, 40);
txt.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
if(e.getKeyChar() == 29){
ta.append("\n GS1 on position = " + i);
}
i++;
}
});
f.add(txt);
JButton b = new JButton("Clear");
b.addActionListener(e -> {
ta.setText("");
txt.setText("");
i = 0;
});
b.setBounds(130,80,100, 40);
f.add(b);
ta.setBounds(50, 130, 400, 300);
f.add(ta);
f.setSize(600,500);
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public void show()
{
f.setVisible(true);
}
}
can someone help me on this ?