2017-01-14 37 views
0

请考虑以下的项目结构如何通过CSS添加外部图像

base_folder 
      | 
      |_ MyApp 
      | | 
      | |_ src 
      |  | 
      |  |_controllers (Controllers) 
      |    |_MyClass.java 
      | 
      |_ themming 
       | 
       |_ icons 
       |  | 
       |  |icon.png 
       | 
       |_ style (css) 
        | 
        |_myStyle.css 

MyClass.java

HBox root = new HBox(); 
Scene scene = new Scene(root, 800, 605); 

File f = new File("../themming/style/myStyle.css"); 
try { 
    root.getStylesheets().setAll(f.toURI().toURL().toExternalForm()); 
} catch (MalformedURLException e) { 
    e.printStackTrace(); 
} 

root.getStyleClass().add("custom-background"); 

myStyle.css

.custom-background { 
    -fx-padding: 15; 
    -fx-spacing: 10; 
    -fx-font-size: 17pt; 
    -fx-background-image: url("../icons/icon.png")); 
    -fx-background-size: 22 22; 
    -fx-background-position: 0 0; 
    -fx-background-repeat: no-repeat; 
} 

其他所有风格的课程都获得照片除了与图像有关的任何事情之外。

我试过可以的URL的所有变化:

File f = new File("themming/style/myStyle.css"); 
File f = new File("../themming/style/myStyle.css"); 
File f = new File("../../themming/style/myStyle.css"); 

,甚至把相对于项目的根目录不同的位置themming,但都没有成功。

我在这一切中失去了什么?我究竟做错了什么?

谢谢大家提前。

+0

没有'icon.png'显示的文件树 – Tunaki

+0

对不起。我编辑了这个问题。 –

+0

不过,不显示''images/icon.png'。但无论如何,'themming'文件夹是源文件夹吗?你如何运行应用程序? – Tunaki

回答

0

尝试这样的:

.custom-background { 
-fx-padding: 15; 
-fx-spacing: 10; 
-fx-font-size: 17pt; 
-fx-background-image: url("../icons/icon.png")); 
-fx-background-size: 22 22; 
-fx-background-position: 0 0; 
-fx-background-repeat: no-repeat; 
} 
0

为什么不使用这种方法直接:

/* "pathToTheMainFolder" : All directories before reaching "themming" */ 
String path = "file:C:/Users/UserName/pathToTheMainFolder/themming/style/style.css"; 
root.getStylesheets().add(path); 

和图标应该是相对于您的css文件所在位置:

.custom-background{ 
/*return to the previous folder "themming" and enter to "icons"*/ 
-fx-background-image:url("..//icons/icon.png"); 
} 

注意:对于第一个路径(css文件),您可以使用该方法那@fabian建议你Here.

相关问题