更改进度条javaFX的样式

Change style of progressbar javaFX

ProgressBar 的默认外观是随着进度增加在控件上移动的蓝色条:

我的应用程序中有一张(火车的)图像作为资源。是否有可能使用 CSS (或其他技术)使图像在控件中而不是默认的蓝色条上前进?它应该看起来像:

只需使用外部 CSS 文件并在栏中设置背景图像。条形图本身由 Region 表示,样式为 class bar(参见 docs),因此您只需要

.progress-bar > .bar {
    -fx-background-image: url("http://upload.wikimedia.org/wikipedia/commons/c/ce/Train_icon_small.png");
    -fx-background-position: right ;
    -fx-background-color: transparent ;
    -fx-background-repeat: repeat-x ;
}

完整示例:

import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;


public class TrainProgressBar extends Application {

    @Override
    public void start(Stage primaryStage) {
        ProgressBar progressBar = new ProgressBar();
        progressBar.setProgress(0);
        Button startButton = new Button("Start");
        startButton.setOnAction(e -> {
            startButton.setDisable(true);
            Task<Void> task = new Task<Void>() {
                @Override
                public Void call() throws Exception {
                    for (int i = 0; i < 100; i++) {
                        Thread.sleep(20);
                        updateProgress(i, 100);
                    }
                    updateProgress(100, 100);
                    return null ;
                }
            };
            progressBar.progressProperty().bind(task.progressProperty());
            task.setOnSucceeded(evt -> startButton.setDisable(false));
            new Thread(task){{setDaemon(true);}}.start();
        });

        VBox root = new VBox(15, progressBar, startButton);
        Scene scene = new Scene(root, 250, 100);
        scene.getStylesheets().add("train-progress-bar.css");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

训练进度-bar.css:

.root {
    -fx-padding: 10 ;
    -fx-alignment: center ;
}

.progress-bar > .bar {
    -fx-background-image: url(http://upload.wikimedia.org/wikipedia/commons/c/ce/Train_icon_small.png);
    -fx-background-position: right ;
    -fx-background-color: transparent ;
    -fx-background-repeat: repeat-x ;
}
   .parentOfProgress {
    padding: 1px;
    border: 1px solid #808080;
    width: 144px;
}
progress {
    height:5px !important;
    background: #fafafa !important;
}

    progress::-webkit-progress-bar {
        background: #fafafa !important;
        height: 5px !important;
    }

    progress::-webkit-progress-value {
        background: #06c !important;
    }

    progress::-moz-progress-bar {
        background: #fafafa !important;
        height: 5px !important;
    }