Handle barcode scan in Java

前端 未结 4 651
长情又很酷
长情又很酷 2021-01-16 06:57

I want to have my application react to barcodes being scanned to trigger button presses. For example the user could scan the ((PRINT)) barcode to activate the print button.<

4条回答
  •  臣服心动
    2021-01-16 07:51

    Correct me if I missunderstood, but it sounds like you have a barcode-scanner which will enter text into a field. But you want to be alerted when the text in the field equals something (so an action can take place) regardless of how it was entered (by barcode scanner or key press).

    I'd recommend using a DocumentListener to alert you of changes to the text field - this should work with both of your requirements.

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    
    public class TempProject extends Box{
    
        public TempProject(){
            super(BoxLayout.Y_AXIS);
            final JTextArea ta = new JTextArea();
            ta.getDocument().addDocumentListener(new DocumentListener(){
    
                @Override
                public void changedUpdate(DocumentEvent arg0) {
                    doSomething();
                }
    
                @Override
                public void insertUpdate(DocumentEvent arg0) {
                    doSomething();
                }
    
                @Override
                public void removeUpdate(DocumentEvent arg0) {
                    doSomething();
                }
    
                public void doSomething(){
                    if(ta.getText().equalsIgnoreCase("print")){
                            System.out.println("Printing...");
                            //Need to clear text in a separate swing thread
                            SwingUtilities.invokeLater(new Runnable(){
                                @Override
                                public void run() {
                                    ta.setText("");
                                }});
                    }
                }
    
            });
    
            add(ta);
        }
    
    
        public static void main(String args[])
        {
            EventQueue.invokeLater(new Runnable()
            {
                public void run()
                {
                    JFrame frame = new JFrame();
                    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
                    frame.setContentPane(new TempProject());
                    frame.setPreferredSize(new Dimension(500, 400));
                    frame.pack();
                    frame.setVisible(true);
                }
            });
        }   
    
    
    }
    

提交回复
热议问题