Saboor880 9 Junior Poster

Hi developers! I have made a POS software. I have added the functionality of "priniting to Thermal printer" and "barcodes". Firstly I added the functionality of Reciept printing which worked perfectly. Then I added the functionality of barcode scanning. As you know barcode reader device automatically scans the barcode and write the barcode in Text field or excel sheet. But in the sales screen , all the field of item/product should be populated from database When barcode is scanned. I implemented an interface(I get this code form internet) in the my Sales Screen Constructor. It workded perfectly for me, but after adding this interface, my Printing functionality malfunctioned.i-e after sending Print command to the Printer, Printer just waits and does not print any thing and the Printer status remains constant i-e"Printing".

But if I remove the Barcode scanning interface, The Printer works fine again, I want to know that why Implementation of Barcode scanning Interface, printer stops working? I think that the barcode scanning Interface (which i implemented) keeps a port busy , But I am not sure which port and why?

I am also giving the code of implementation of barcode scanning.

private AWTEventListener barcodeListener=null;

//now implementing the interface.
barcodeListener= (new BarcodeAwareAWTEventListener(new BarcodeCapturedListener() {
            @Override
            public void barcodeCaptured(String barcodeString) {
                   char[] strArray;
                 // JOptionPane.showMessageDialog(Sale.this, "barcode captured: "+barcodeString);
                 strArray = barcodeString.toCharArray(); 

        StringBuffer stringBuffer = new StringBuffer(); 

                 for (int i = 0; i < strArray.length; i++) {  
            if ((Integer.valueOf(strArray[i])!=32)) {  
                stringBuffer.append(strArray[i]);  
            }  
          }  

                String noSpaceStr = stringBuffer.toString();  

               char[] strArray2 = noSpaceStr.toCharArray(); 
              StringBuffer stringBuffer2 = new StringBuffer();
              for (int i = 0; i < strArray2.length; i++) {  
            if ((Integer.valueOf(strArray2[i])!=8)) {  
                stringBuffer2.append(strArray2[i]);  
            }  
          }  
              String noSpaceStr2 = stringBuffer2.toString();
             // JOptionPane.showMessageDialog(Sale.this, "barcode found: "+noSpaceStr2);

                try {
                    String itmName = obj.selectSingleItemByProductCode(noSpaceStr2);
                 //   JOptionPane.showMessageDialog(Sale.this, "product corresponding to code: "+itmName);
                    if(itmName.equals("")||itmName==null){
                       JOptionPane.showMessageDialog(Sale.this, "No Product found for this barcode.\n"
                               + "Try again to scan the barcode on Product.\n               OR\n check that whether you "
                               + "have entered the product\nwith this barcode in the inventory or not","Error",JOptionPane.ERROR_MESSAGE);
                    }
                    else{
                          // populating  the UI if barcode exists in database on successful barcode scann.
                       jComboBoxItem.setSelectedItem(itmName);
                     double tq = obj.SelectSumOfInventory(itmName);
                      txtfAvailQnt.setText(String.valueOf(tq));
                      sp= obj.getLatestSP(noSpaceStr2,itmName);
                      txtfSP.setText(String.valueOf(sp));

                       stringBuffer= new StringBuffer();
                       stringBuffer.append("");
                       stringBuffer2 = new StringBuffer();
                       stringBuffer2.append("");
                       itmName="";

                    }
                } catch (SQLException ex) {
                    Logger.getLogger(Sale.class.getName()).log(Level.SEVERE, null, ex);
                }

           }
        }));

          // Now adding the interface. 

       Toolkit.getDefaultToolkit().addAWTEventListener(barcodeListener, AWTEvent.KEY_EVENT_MASK);

Dani AI

Generated

— most cases where adding a global AWT-based barcode listener suddenly makes printing hang come down to threading and blocking, not a mysterious “port lock.” The AWTEventListener callbacks run on the Event Dispatch Thread (EDT). If the listener does database lookups, shows modal dialogs (JOptionPane) or otherwise performs long work on the EDT, it will block other UI/spool-related work and can make print jobs appear to stall in “Printing.”

Quick isolation steps:

  • Temporarily remove or disable the listener and retry printing. If printing works, the listener is involved.
  • Replace the listener body with the absolute minimum (e.g., log the raw barcode string) and test again.
  • Check for modal dialogs or synchronized blocks inside the listener that could block other threads.

Fix pattern (keep the listener fast; push heavy work off the EDT). Example approach: assemble the barcode quickly in the listener, then submit the DB/lookup work to a background executor and update Swing components via SwingUtilities.invokeLater (or use SwingWorker). Do not show modal dialogs from inside the listener.

final ExecutorService bg = Executors.newSingleThreadExecutor();

Toolkit.getDefaultToolkit().addAWTEventListener(ev -> {
    String code = quickExtractBarcode(ev); // must be fast; no DB here
    if (code == null) return;

    bg.submit(() -> {
        String item = findItemInDatabase(code); // background DB call
        SwingUtilities.invokeLater(() -> {
            if (item != null) {
                jComboBoxItem.setSelectedItem(item);
                txtfAvailQnt.setText(String.valueOf(getQty(item)));
            } else {
                // update a status label instead of blocking dialog
                statusLabel.setText("No product for: " + code);
            }
        });
    });
}, AWTEvent.KEY_EVENT_MASK);

Other checks: ensure the listener does not call KeyEvent.consume() in a way that interferes with other input, confirm the scanner mode (keyboard wedge vs serial) so it isn’t sharing a serial port with the printer, add robust logging and catch all exceptions in the listener, and take a thread dump (jstack/VisualVM) while the print job is stuck to see blocked threads.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.