我正在开发一个应用程序,使用java-simple-serial-connector API读取 并写入串行端口。当我尝试读取数据字节 并将它们分配给全局字符串变量(sReader)时,我遇到了问题。 sReader不会获得整个字符串,并且其长度每次都是随机的。我相信我收到所有的字节,因为当我将字符串sBuffer附加到Output(Output.append)时,总是显示整个字符串。请看看我的示例代码如下:java - 无法在invokeAndWait中赋值给全局字符串变量
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) {
}
}
}
}
}
}
请注意'Output'是一个实例变量,按照惯例,应该以小写字母开头。 – DNA 2012-02-28 20:56:01
感谢您注意到,这是一个意外,因为我正在快速键入示例 – jadrijan 2012-02-28 20:58:32