JavaFX FXML 背景图像:如何 select 从文件夹中提取图像而不确切知道其名称?

JavaFX FXML Background Image: How to select an image from a folder without knowing exactly its' name?

我正在尝试将 JavaFX 程序的背景图像设置为与用户背景相同。

windows 中的背景图片位于:“%AppData%\Microsoft\Windows\Themes\CachedFiles”

并使用 JavaFX 我使用以下方法添加了样式:

style="-fx-background-image: url('%AppData%\Microsoft\Windows\Themes\CachedFiles\*.jpg');"

我应该用什么替换'*.jpg'(知道那里只有1张照片)?或者我该如何解决这个问题?

单靠 FXML 是做不到的。加载 FXML 后,您需要从控制器设置背景。

FXML:

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.control.PasswordField?>
<?import javafx.scene.control.Button?>
<AnchorPane fx:controller="Whosebug.answers.demo.Main$Controller" fx:id="mainPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <TextField fx:id="username" layoutX="30.0" layoutY="125.0" />
      <Label layoutX="30.0" layoutY="99.0" text="Username" />
      <Label layoutX="30.0" layoutY="174.0" text="Password" />
      <PasswordField fx:id="password" layoutX="30.0" layoutY="200.0" />
      <Button fx:id="login" layoutX="61.0" layoutY="338.0" mnemonicParsing="false" text="Login" />
   </children>
</AnchorPane>

代码:

public class Main extends Application {

    public static class Controller {

        @FXML
        AnchorPane mainPane;
        @FXML
        TextField username;
        @FXML
        PasswordField password;
        @FXML
        Button login;
    }

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

    private Optional<String> pickRandomImage() {
        File[] imgs =  Paths.get(System.getenv("APPDATA"), "Microsoft", "Windows", "Themes", "CachedFiles")
             .toFile().listFiles((File f) -> f.getName().endsWith(".jpg"));
        if (imgs != null && imgs.length > 0) {
            Collections.shuffle(Arrays.asList(imgs));
            return Optional.of(imgs[0].toURI().toString());
        }
        return Optional.empty();
    }

    @Override
    public void start(Stage stage) {
        stage.setTitle("Random Background");
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/layout.xml"));
        try {
            Parent root = loader.load();
            Controller ctrl = loader.getController();
            pickRandomImage().ifPresent(imgurl -> {
                Image image = new Image(imgurl);
                ctrl.mainPane.setBackground(new Background(new BackgroundImage(image, BackgroundRepeat.REPEAT, BackgroundRepeat.REPEAT, BackgroundPosition.CENTER, BackgroundSize.DEFAULT)));
            });
            Scene scene = new Scene(root);
            stage.setScene(scene);
            stage.show();
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

请注意,如果存在多张图片,我的示例将从文件夹中随机选择一张图片。您可以删除该部分或保留它,因为如果只有一张图像,它不会影响结果。