我的问题很直截了当(我只是个玩玩的休闲编码员)。我已经建立了与API的连接,并且通过RxJava的魔力,我可以订阅API发出的json数据。我还使用FXML创建了一个非常基本的GUI。
每次通过订阅发出事件时,如何使TextArea = textAreaA中的文本更新?换句话说,如何使TextArea显示API提要?
我从头到尾都阅读了RxJavaFx指南,它似乎更关注事件从Fx到Rx的定向流:(
这是我的代码示例:
public class Tester extends Application{
private static final Logger LOG = LoggerFactory.getLogger(Tester.class);
public static void main(String[] args) throws IOException, InterruptedException{
launch(args);
}
public void start (Stage primaryStage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml"));
Parent root = loader.load();
primaryStage.setTitle("App Window");
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
TESTER_API.TESTER_API_Connector();
}
}
public class TESTER_API {
public static void TESTER_API_Connector() throws IOException, InterruptedException {
StreamingEvents emissions = StreamingEventsFactory.INSTANCE.createEvents(TheseStreamingEvents.class.getName());
emissions.connect().blockingAwait();
emissions.getEvents().getSomethingSpecific()
.subscribe(event -> System.out.println(event.getSomethingSpecific()) // Here is the event that I would like to bind or otherwise push to textAreaA in the FXML controller
,throwable -> new Exception("GUI error!"));
}
}
public class FXMLDocumentController implements Initializable {
@FXML
public TextArea textAreaA;
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:0)
我的想法是让TESTER_API
调用FXMLDocumentController
中的一个函数来更新textAreaA
。我建议使用Platform.runLater()
来确保线程安全。
public class Tester extends Application{
[...]
public void start (Stage primaryStage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml"));
Parent root = loader.load();
FXMLDocumentController controller = loader.getController();
primaryStage.setTitle("App Window");
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
TESTER_API.TESTER_API_Connector(controller);
}
}
public class TESTER_API {
public static void TESTER_API_Connector(FXMLDocumentController controller) throws IOException, InterruptedException {
[...]
emissions.getEvents().getSomethingSpecific()
.subscribe(event -> Platform.runLater(() -> {
controller.updateTextArea(event.getSomethingSpecific());
}),
throwable -> new Exception("GUI error!"));
}
}
public class FXMLDocumentController implements Initializable {
@FXML
public TextArea textAreaA;
[...]
public void updateTextArea(String string) {
textAreaA.setText(string);
}
}