2017-01-14 10 views
0

myStyle.cssは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; 
} 

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"); 

では、次のプロジェクト構造

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

をご検討ください他のすべてのスタイルクラスは写真を取得しますイメージとは何か関係がありません。

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 を置く、ない成功へ:

は、私は可能なURLのすべてのバリエーションを試してみました。

私はこれで何が欠けていますか?私は間違って何をしていますか?

ありがとうございます。

+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.

関連する問題