2012-03-16 55 views

回答

27

的方法之一可以是這樣的:

1)創建具有名稱 「的style.css」 CSS文件,並定義在它的id選擇:

#pane{ 
    -fx-background-image: url("background_image.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); 
} 

2 )使用CSS中定義的值設置場景中最頂級控件(或任何控件)的id,並將此CSS文件加載到場景中:

public class Test extends Application { 

    public static void main(String[] args) { 
     launch(args); 
    } 

    @Override 
    public void start(Stage primaryStage) { 
     StackPane root = new StackPane(); 
     root.setId("pane"); 
     Scene scene = new Scene(root, 300, 250); 
     scene.getStylesheets().addAll(this.getClass().getResource("style.css").toExternalForm()); 
     primaryStage.setScene(scene); 
     primaryStage.show(); 
    } 
} 

你也可以給一個ID在FXML文件中的控制:

<StackPane id="pane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml" fx:controller="demo.Sample"> 
    <children> 
    </children> 
</StackPane> 

有關JavaFX的CSS樣式參照本guide更多信息。

+0

我張貼另一個問題前面請在這裏幫助http://stackoverflow.com/questions/9736393/javafx-2鏈接-not-resizing-ui-control-based-on-window-size – John 2012-03-16 17:30:04

+0

可以從另一個函數改變場景背景,除了void start – Ossama 2014-03-22 02:56:36

+0

@Ossama是的,你可以。定義兩個不同的CSS選擇器(具有兩個不同的背景特徵),並在某些方法中用所需的方法更改節點的ID。 – 2014-03-22 03:51:42

10

您可以使用.root類現場直接改變風格:

.root { 
    -fx-background-image: url("https://www.google.com/images/srpr/logo3w.png"); 
} 

一下添加到CSS並加載它作爲「Uluk BIY」,在他的回答中描述。

+0

糟糕!我怎樣才能讓圖像充滿整個場景?它在左側和頂部留下白色空間。 – John 2012-03-16 20:15:31

+0

'-fx-background-repeat:stretch; ' – 2012-03-16 21:59:12

+0

它仍然留下空間。場景的根源是一個GridPane,我正在將場景中的gridpane對中。我怎樣才能防止背景圖像居中? – John 2012-03-16 22:46:16

19

我知道這是一個老問題

,但如果你想以編程方式做到這一點或Java的方式

圖像背景;您可以使用BackgroundImage

BackgroundImage myBI= new BackgroundImage(new Image("my url",32,32,false,true), 
     BackgroundRepeat.REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT, 
      BackgroundSize.DEFAULT); 
//then you set to your node 
myContainer.setBackground(new Background(myBI)); 

對於油漆或填充背景;你可以使用BackgroundFill

BackgroundFill myBF = new BackgroundFill(Color.BLUEVIOLET, new CornerRadii(1), 
     new Insets(0.0,0.0,0.0,0.0));// or null for the padding 
//then you set to your node or container or layout 
myContainer.setBackground(new Background(myBF)); 

保持你的java活着& &你的CSS死..