我正在使用java-simple-serial-connector API开发一个应用程序来读取 并写入串口。当我尝试读取数据字节时,我遇到了问题 并将它们分配给全局String变量(sReader)。 sReader没有得到整个字符串,每次长度都是随机的。我确信我正在接收所有字节,因为当我将字符串sBuffer附加到Output(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) {
}
}
}
}
}
}
答案 0 :(得分:1)
我假设您希望从代码的其他部分访问sReader。在这种情况下,请考虑使sReader易变,并在制作Runnable之前分配它。另外,如果sBuffer仅用于在Runnable中使用String,请考虑将其作为最终的局部变量。
private volatile String sReader = "";
...
final String sBuffer = new String(bBuffer);
sReader = sBuffer;
SwingUtilities.invokeAndWait(
...