Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7566685
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T14:28:37+00:00 2026-05-30T14:28:37+00:00

My application is supposed to read and write to a Serial Port. The data

  • 0

My application is supposed to read and write to a Serial Port. The data is read in the EventListener of the PortReader class. I wish to assign this data to a global String variable (private String sPortReaderString) for further use. The global string variable should return its value by using a method called getPortReader() which simply returns the string sPortReaderString. In the application’s JFrame I open the serial port connection, send a command for which I automatically receive a reply from serial device, and I display that reply output in a label. The problem is that the label is always blank since the sPortReaderString returned from getPortReader() has nothing assigned to it. I am very sure that the sPortReaderString gets assigned a value in the EvenListener. The problem seems to be that the method getPortReader() in the JFrame is called before any value had enough time to get assigned to sPortReaderString. Please take a look at my otuput and the code below:

The following is the output I get:

sPortReaderString:
PortReader

Short example of portsMethod in JFrame:

public class MyJFrame extends javax.swing.JFrame {

    public MySerialPort msp = new MySerialPort();   

    public MainJFrame() {
        portsMethod();
    }

    private void portsMethod() {

        msp.getPortNames();//Gets the name of the port (COM1 in my case)
        msp.openPort();//Opens COM1 port
        msp.getFirmwareVersion();//Prompts for device firmware version by sending a string command
        msp.getPortReader();//Reads the reply from device

    }

}

The following is the example of my Serial Port class:

public class MySerialPort {

    private SerialPort serialPort;
    private int iBaudRate = SerialPort.BAUDRATE_57600;
    private int iDataBits = SerialPort.DATABITS_8;
    private int iStopBits = SerialPort.STOPBITS_1;
    private int iParity = SerialPort.PARITY_NONE;
    private String sPortName;
    private String sPortReaderString = "";
    private StringBuilder sbPortReaderString = new StringBuilder();

    public void getFirmwareVersion() {
        sendPortCommand("<FirmVer>\r\n");
    }

    public void clearPortReader() {
        sbPortReaderString.setLength(0);
    }

    public String getPortReader() {
        System.out.print("sPortReaderString: " + sPortReaderString);
        return sPortReaderString;
    }

    public void getPortNames() {
        String[] sPorts = SerialPortList.getPortNames();
        sPortName = sPorts[0];
    }

    public void openPort() {

        serialPort = new SerialPort(sPortName);

        try {

            if (serialPort.openPort()) {

                if (serialPort.setParams(iBaudRate, iDataBits, iStopBits, iParity)) {

                    serialPort.addEventListener(new PortReader(), SerialPort.MASK_RXCHAR
                            | SerialPort.MASK_RXFLAG
                            | SerialPort.MASK_CTS
                            | SerialPort.MASK_DSR
                            | SerialPort.MASK_RLSD);

                } else {
                    serialPort.closePort();
                }

            } else {}
        } catch (SerialPortException | HeadlessException ex) {}
    }

    private void sendPortCommand(String sSendPortCommand) {

        if (sSendPortCommand.length() > 0) {
            try {
                serialPort.writeBytes(sSendPortCommand.getBytes());
            } catch (Exception ex) {}
        }
    }

    private class PortReader implements SerialPortEventListener {

        private String sBuffer = "";

        @Override
        public void serialEvent(SerialPortEvent spe) {

            if (spe.isRXCHAR() || spe.isRXFLAG()) {

                if (spe.getEventValue() > 0) {

                    try {

                        //Read chars from buffer
                        byte[] bBuffer = serialPort.readBytes(spe.getEventValue());
                        sBuffer = new String(bBuffer);

                        SwingUtilities.invokeAndWait(
                                new Runnable() {

                                    @Override
                                    public void run() {
                                        sbPortReaderString.append(sBuffer);
                                    }
                                });

                        sPortReaderString = new String(sbPortReaderString);
               //if I print sPortReaderString in here it is not blank and has the correct value

                        System.out.print("PortReader");

                    } catch (SerialPortException | InterruptedException | InvocationTargetException ex) {
                    }
                }
            }
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T14:28:39+00:00Added an answer on May 30, 2026 at 2:28 pm

    It seems pretty logical to me:

    You have a first event handling method execution in the EDT which gets the firmware version and then gets the port reader. Getting the firmware version causes an event to be received, in a different thread (and thus in parallel to the execution of portsMethod() in the EDT).

    The event handling code invokes SwingUtilities.invokeAndWait(). This call thus waits for the first event handling methd to complete, and then appends the received string to sbPortReaderString. This append is thus done after the portsMethod has completed.

    The serial port offers an event-based mechanism. I would simply use it to propagate the event to one or several listeners in the EDT:

    // accessed only from the EDT
    private List<MyPortListener> portListeners = new ArrayList<MyPortListener>();
    
    public void addMyPortListener(MyPortListener listener) {
        portListeners.add(listener);
    }
    
    public void removeMyPortListener(MyPortListener listener) {
        portListeners.remove(listener);
    }
    
    ... 
    
        @Override
        public void serialEvent(SerialPortEvent spe) {
            ...
            final String receivedString = ...;
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    for (MyPortListener listener : portListeners) {
                        listener.stringReveivedFromSerialPort(receivedString);
                    }
                }
            });
        }
    

    Side note: your code is hard to understand mainly because your variables and methods are badly named.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm supposed to modify an application written in 16-bit assembly which uses serial port.
I am trying to write a metro style application to read data from a
I'm using boost::property_tree to read and write XML configuration files in my application. But
I'm working on an application that's supposed to read and process flat files. These
my web application supposed to send email reminders in some point it will send
I want to create a very basic 3D modeling tool. The application is supposed
I have an application that is supposed to aid my project in terms of
I'm working on an application that is supposed to create products (like shipping insurance
There is a console Java application which is supposed to run until it is
I'm writing a Windows Forms application which is supposed to play three sound files

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.