2016-05-19 30 views
2

我想在使用JavaFx創建的GUI中添加圖像。我的JavaFx如下:在JavaFx中添加圖片Gui

StackPane layoutTSignUp = new StackPane(); 
layoutTSignUp.setStyle("-fx-background-color: #FFFF;"); 

我怎樣才能代替顏色我可以添加圖像。此外,我怎麼能達到同樣的在我的按鈕:

teacherButton.setStyle("-fx-font: 45 Arial; -fx-base: #FFFF"); 
+0

你關於按鈕中的圖像的第二個問題是重複的:[JavaFX - 創建自定義按鈕與圖像](http://stackoverflow.com/questions/10518458/javafx-create-custom-button-with-image) – jewelsea

回答

2

編程方式

爲了您StackPane你可以使用BackgroundImage類:

BackgroundImage backgroundImage= new BackgroundImage(new Image(getClass().getResource("thinking-man.jpg").toExternalForm(),32,32,false,true), 
       BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT, 
       BackgroundSize.DEFAULT); 

stackPane.setBackground(new Background(backgroundImage)); 

對於按鈕:按鈕有一個graphic屬性:

button.setGraphic(new ImageView(new Image(getClass().getResource("thinking-man.jpg").toExternalForm()))); 

使用CSS

如果您更喜歡使用樣式表來設置背景圖片,你可以使用:

-fx背景圖像,-fx背景重複,-fx背景位置和-fx-background-size

For details you can read the JavaFX CSS reference for Region class.

使用相同的例子與StackPane

stackPane.getStylesheets().add(getClass().getResource("application.css").toExternalForm()); 
stackPane.getStyleClass().add("stackpane-with-background"); 

application.css

.stackpane-with-background{ 
    -fx-background-image: url("thinking-man.jpg"); 
    -fx-background-repeat: stretch; 
    -fx-background-size: 900 506; 
    -fx-background-position: center center; 
    -fx-effect: dropshadow(three-pass-box, black, 30, 0.5, 0, 0); 
} 

希望這有助於。