因此,我使用此链接来设置进度条,并且在运行此代码时效果很好。
但是,使用我拥有的设置,我似乎无法获得progressbar进行实际更新… progressBar.getProgress()实际上获得了正确的进度,但是UI并未更新。这是到目前为止的代码:
Main.java
public class Main extends Application { @Override public void start(Stage primaryStage) { try { FXMLLoader loader = new FXMLLoader(Main.class.getResource("ProgressBarLayout.fxml")); AnchorPane root = (AnchorPane) loader.load(); Scene scene = new Scene(root); primaryStage.setScene(scene); primaryStage.show(); } catch(Exception e) { e.printStackTrace(); } } public static void main(String[] args) { launch(args); } }
ProgressBarController.java
public class ProgressBarController { private Task copyWorker; @FXML private ProgressBar progressBar; @FXML private void onButtonClick() { progressBar = new ProgressBar(0); progressBar.setProgress(0); copyWorker = createWorker(); progressBar.progressProperty().unbind(); progressBar.progressProperty().bind(copyWorker.progressProperty()); new Thread(copyWorker).start(); } public Task createWorker() { return new Task() { @Override protected Object call() throws Exception { for (int i = 0; i < 10; i++) { Thread.sleep(2000); updateMessage("2000 milliseconds"); updateProgress(i + 1, 10); System.out.println(progressBar.getProgress()); } return true; } }; } }
ProgressBarLayout.fxml
<?xml version="1.0" encoding="UTF-8"?> <?import java.lang.*?> <?import javafx.scene.control.*?> <?import javafx.scene.layout.*?> <?import javafx.scene.layout.AnchorPane?> <AnchorPane prefHeight="257.0" prefWidth="434.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.ProgressBarController"> <children> <ProgressBar fx:id="progressBar" layoutX="54.0" layoutY="103.0" prefHeight="51.0" prefWidth="326.0" progress="0.0" /> <Button layoutX="201.0" layoutY="182.0" mnemonicParsing="false" onAction="#onButtonClick" text="OK" /> </children> </AnchorPane>
在您的控制器中,您可以执行以下操作:
progressBar = new ProgressBar(0);
这意味着它将创建一个新的ProgressBar实例,并且将不再使用FXML中的progressBar。只需删除此行,它应该可以工作