JavaFXML背景图像:如何从文件夹中选择图像而不确切知道其名称?
我试图将JavaFX程序的背景图像设置为与用户背景相同的图像 windows中的背景图像位于:%AppData%\Microsoft\windows\Themes\CachedFile中 使用JavaFX,我添加了以下样式:JavaFXML背景图像:如何从文件夹中选择图像而不确切知道其名称?,java,css,javafx,fxml,Java,Css,Javafx,Fxml,我试图将JavaFX程序的背景图像设置为与用户背景相同的图像 windows中的背景图像位于:%AppData%\Microsoft\windows\Themes\CachedFile中 使用JavaFX,我添加了以下样式: style="-fx-background-image: url('%AppData%\Microsoft\Windows\Themes\CachedFiles\*.jpg');" 我应该用知道那里只有一张照片来替换“*.jpg”吗?或者我该如何解决这
style="-fx-background-image: url('%AppData%\Microsoft\Windows\Themes\CachedFiles\*.jpg');"
我应该用知道那里只有一张照片来替换“*.jpg”吗?或者我该如何解决这个问题?单靠FXML是做不到的。加载FXML后,需要从控制器设置背景 FXML: 代码:
请注意,如果存在多个图像,我的示例将从文件夹中随机选取一个图像。你可以去掉那个部分,或者留下它,因为如果只有一个图像,它不会影响结果。只是好奇:你为什么不知道它的确切名称?至少在运行时,它应该是可用的还是不可用的?我想让每个打开它的人都有一个不同的背景图像。因此,如果设置了不同的背景,我的电脑上应用程序的背景图像将与你的电脑上的不同。你希望你的程序在CachedFiles文件夹中选择随机背景吗?
<?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="stackoverflow.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);
}
}
}