将串口接收到的数据发送到 JavaFX 控制器

Send data received on serial port to JavaFX controller

我正在尝试从串行端口读取数据并将其显示在 JavaFX 控制器中。我正在使用 jSerialComm 从串口读取数据。这是他们的例子:

public final class MessageListener implements SerialPortMessageListener {
    @Override
    public int getListeningEvents() { return SerialPort.LISTENING_EVENT_DATA_RECEIVED; }

    @Override
    public byte[] getMessageDelimiter() { return new byte[] { (byte) 0x03}; }

    @Override
    public boolean delimiterIndicatesEndOfMessage() { return true; }

    @Override
    public void serialEvent(SerialPortEvent event) {
        byte[] delimitedMessage = event.getReceivedData();
        System.out.println("Received the following delimited message: " + new String(delimitedMessage));
    }
}

然后将串行事件附加到 com 端口:

static public void main(String[] args) {
    SerialPort comPort = SerialPort.getCommPorts()[0];

    comPort.setBaudRate(1200);
    comPort.openPort();
    comPort.addDataListener(new MessageListener());
}

serialEvent方法中,数据打印在控制台中。如何将此事件中收到的数据发送到 JavaFX 控制器?

不太清楚你在问什么:你已经有了所有的部分。

我不熟悉 jSerialComm(尤其是它如何管理线程),但您的 JavaFX 应用程序将如下所示:

public class MyApp extends Application {
    private SerialPort comPort;

    public static void main(String[] args) {
        Application.launch(args);
    }

    @Override
    public void init() {
        comPort = SerialPort.getCommPorts()[0];

        comPort.setBaudRate(1200);
        comPort.openPort();
    }

    @Override
    public void start(Stage stage) {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/path/to/fxml/file"));
        Parent root = loader.load();
        MyControllerClass controller = loader.getController();

        SerialPortMessageListener listener = new SerialPortMessageListener() {
            @Override
            public int getListeningEvents() { return SerialPort.LISTENING_EVENT_DATA_RECEIVED; }

            @Override
            public byte[] getMessageDelimiter() { return new byte[] { (byte)0x03}; }

            @Override
            public boolean delimiterIndicatesEndOfMessage() { return true; }

            @Override
            public void serialEvent(SerialPortEvent event) {
                byte[] delimitedMessage = event.getReceivedData();
                Platform.runLater(() -> controller.processData(new String(delimitedMessage)));
            }
        }

        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
    }

    @Override
    public void stop() {
        // shut down comPort
    }
}

public class MyControllerClass {
    @FXML
    private TextArea textArea;

    public void processData(String data) {
        textArea.appendText(data);
    }

    // other controller stuff
}