【发布时间】:2017-07-20 00:38:50
【问题描述】:
大家。 我有一个程序,它应该自动控制一些机器。我需要 javaFX 来显示车间的临时状态。有几个进程一个接一个地执行,对于每个进程,我需要更新屏幕上的图像(让我们让它更简单,并说我们需要更新标签)。
所以,有一个主线程,它控制机器,还有一个 FX 应用程序线程,它控制 GUI。
public static void main(String[] args) {
//some processes in the main thread before launching GUI (like connecting to the database)
Thread guiThread = new Thread() {
@Override
public void run() {
DisplayMain.launchGUI();
}
};
guiThread.start();
//some processes after launching the GUI, including updating the image on the screen
}
我已经阅读了关于 SO 和 Oracle 文档的大量材料,现在我无法理解所有这些绑定、可观察属性、Platform.runLater、任务、检索控制器、将控制器传递为某个类的参数等
我有一个 fxml 文件,假设它只显示一个标签:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.control.Label?>
<GridPane alignment="center"
hgap="10" vgap="10"
xmlns:fx="http://javafx.com/fxml/1"
xmlns="http://javafx.com/javafx/8"
fx:controller="sample.Controller">
<columnConstraints>
<ColumnConstraints />
</columnConstraints>
<rowConstraints>
<RowConstraints />
</rowConstraints>
<children>
<Pane prefHeight="200.0" prefWidth="200.0">
<children>
<Label fx:id="label" text="Label" />
</children>
</Pane>
</children>
</GridPane>
有一个控制器连接到它。我认为那是我们应该倾听图像变化或其他东西的地方。
package sample;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import java.net.URL;
import java.util.ResourceBundle;
public class Controller implements Initializable {
@FXML
public void initialize(URL location, ResourceBundle resources) {
//some listeners?
}
@FXML
private Label label;
public void setlabel(String s) {
label.setText(s);
}
}
还有一个Display.java用作启动机制。
package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Display extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(loader.load(), 800, 400));
primaryStage.show();
}
static void launchGUI() {
Application.launch();
}
}
最后,问题是:如何从 main() 更新控制器中的标签?有很多关于如何在控制器之间传递数据,如何调用控制器中的方法的信息,但我完全迷失了我的问题。
【问题讨论】:
标签: java multithreading javafx