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) {
}
}
}
}
}
}