我正在开发一个使用 java-simple-serial-connector API 读取和写入串行端口的应用程序。当我尝试读取数据字节并将它们分配给全局字符串变量 (sReader) 时,我遇到了问题。sReader 不会获取整个字符串,并且每次的长度都是随机的。我确信我收到了所有字节,因为当我将字符串 sBuffer 附加到输出 (Output.append) 时,始终会显示整个字符串。请看下面我的示例代码:
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) {
}
}
}
}
}
}