我希望能够通过另一个类对在控制器线程中初始化的FXML文件中定义的JavaFX ProgressBar进行更新。目前,它没有被更新。
test.fxml
<ProgressBar fx:id="progressBar" prefWidth="5000.0" progress="0.0">
<VBox.margin>
<Insets top="3.0" />
</VBox.margin>
</ProgressBar>
Controller.java
@FXML
public static ProgressBar progressBar = new ProgressBar(0);
MyMain main;
@FXML
private void handleStartWork() throws Exception {
new Thread() {
@Override
public void run() {
try {
main = new MyMain();
main.doIt();
} catch (final Exception v) {
// ...
}
}
}.start();
}
MyMain.java
public void doIt(){
while(...){
Platform.runLater(() -> PoCOverviewController.progressBar.setProgress((count / sum) * 100));
}
}
我已经尝试过不同的版本,考虑到类似以下帖子的内容:
- ProgressBar doesn't work with a fxml file and a controller
- How to configure Progress Bar and Progress Indicator of javaFx?
我不知道将ProgressBar设为静态变量是否是正确的方法。我只是不想通过工作流传递对象。
更新(Xavier Lambros回答):现在我尝试使用单例模式,但仍然无法正常工作:
Controller.java
@FXML
public ProgressBar progressBar = new ProgressBar(0);
private static Controller INSTANCE = new Controller();
public static Controller getInstance() {
return INSTANCE;
}
public ProgressBar getProgressBar() {
return progressBar;
}
MyMain.java
public void doIt(){
while(...){
Platform.runLater(() -> Controller.getInstance().getProgressBar()
.setProgress((count / sum) * 100));
}
}
count
和sum
是int
还是long
类型?接下来的问题可能会有所帮助:https://dev59.com/5m445IYBdhLWcg3w0dVD - fabian