【发布时间】:2015-07-11 03:06:11
【问题描述】:
我在 JavaFX 的按钮上设置 backgroundImage 时遇到问题。
Image newGame = new Image("File:/CSS/nova_hra.png");
BackgroundImage newGameBgr = new BackgroundImage(newGame, null, null, null, null);
Button buttonNewGame = new Button("Nová Hra");
Button buttonLoadGame = new Button("Načíst Hru");
Button buttonStatistics = new Button("Statistiky");
Button buttonExit = new Button("Konec");
buttonNewGame.setGraphic(new ImageView(newGame));
//buttonNewGame.setBackground(new Background(newGameBgr));
buttonExit.setMinHeight(40);
buttonLoadGame.setMinHeight(40);
buttonNewGame.setMinHeight(40);
buttonStatistics.setMinHeight(40);
buttonExit.setMinWidth(120);
buttonLoadGame.setMinWidth(120);
buttonNewGame.setMinWidth(120);
buttonStatistics.setMinWidth(120);
这对 buttonNewGame 没有任何作用。每次我尝试用这个加载图像时
Image image = new Image(getClass().getResourceAsStream("a.png"));
我得到了运行时异常。当我使用
Image image = new Image(getClass().getResourceAsStream("a.png"));
整个图像消失了。
【问题讨论】:
-
这两个Image构造函数有什么区别吗?相对于你的班级,你的图片在哪里?
-
我有资源文件夹,里面是 CSS 文件夹,里面是图片。所以绝对路径是 D:/workspace/mazeGame/resources/CSS/nova_hra.png。而我的失败,应该有当我使用 buttonNewGame.setBackground(new Background(newGameBgr));整个图像消失了。
-
因为
getClass().getResourceAsStream()加载了相对于您当前类的资源。getClass().getClassLoader().getResourceAsStream()加载相对于您的类路径根的资源。所以您可能只是使用了错误的路径,您是否验证过您的流!= null? -
当我使用 Image newGame = new Image("File:/CSS/nova_hra.png");图像已加载。我不确定如何验证流!= null。每次我尝试将图像作为流加载时,我都会遇到 runtimeException。
标签: image button background javafx