jadrijan
jadrijan

Reputation: 1446

java - cannot assign value in invokeAndWait to global string variable

I am developing an application using the java-simple-serial-connector API to read and write to serial port. I am facing a problem when I try to read data bytes and assign them to a global String variable (sReader). sReader does not get the whole string and its length is random each time. I am sure that I am receiving all of the bytes because when I append string sBuffer to Output (Output.append) the whole string is displayed always. Please take a look at my sample code below:

public class SerialPortTest extends javax.swing.JFrame {

    private String sReader = "";
    private JTextArea outputTextArea;
    private JLabel outputLabel;

    private class Reader 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() {

                                        sReader = sBuffer;//does not assign full string

                                        outputLabel.setText(sBuffer);//does not set full string

                                        outputTextArea.setText(sBuffer);//does not set full string

                                        outputTextArea.append(sBuffer);//This works! Why the above don't work?

                                    }
                                });

                    } catch (SerialPortException | InterruptedException | InvocationTargetException ex) {
                    }
                }
            }
        }
    }
}

Upvotes: 0

Views: 249

Answers (1)

Clint
Clint

Reputation: 9058

I'm assuming that you want access to sReader from some other portion of the code. In that case consider making sReader volatile and also assigning it before making the Runnable. Also, if sBuffer is only used to make a String to use in the Runnable consider making it a final local variable.

private volatile String sReader = "";
...

final String sBuffer = new String(bBuffer);
sReader = sBuffer;

SwingUtilities.invokeAndWait(
...

Upvotes: 1

Related Questions