Javafx设置背景

标签 java javafx background fxml

我试图在 fxml 的帮助下为我的 borderpane 提供背景。 我有一个 View 和一个 Controller 。 我想你必须在fxml中说:borderPane.setBackground(new Background(myBI));

但我不知道怎么办。 使用 CSS 不是一种选择。

查看:

package application;


import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("Layout_play.fxml"));
        primaryStage.setTitle("Test");
        primaryStage.setFullScreen(true);
        primaryStage.setScene(new Scene(root, 1280, 720));
        primaryStage.show();
    }


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

Controller :

public class PlayController {

    @FXML
    private Label label;
    @FXML
    private TextField textfield;

    @FXML
    private BackgroundImage myBI= new BackgroundImage(new Image("/Background.png",1280,720,false,true),
            BackgroundRepeat.REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT,
              BackgroundSize.DEFAULT);



    @FXML
    private void handleButtonAction(ActionEvent event) {
        System.out.println("You clicked me!");
        label.setText("Hello  " + textfield.getText());
    }
}

和最后一个 fxml

<BorderPane fx:controller="application.PlayController" xmlns:fx="http://javafx.com/fxml"
    prefHeight="200" prefWidth="320" >

    <top>
        <Text text="java-Buddy"/>
    </top>
    <left>
        <Label text="Who are you?"/>
    </left>
    <center>
        <TextField id="textfield" fx:id="textfield"/>
    </center>
    <right>
        <Button id="button"  text="Click Me!"
            onAction="#handleButtonAction" fx:id="button"/>
    </right>
    <bottom>
        <Label id="label" fx:id="label"/>
    </bottom>

</BorderPane>

最佳答案

由于您无法使用 CSS,所以这不会很漂亮。

您已经将 BackgroundImage 定义为 myBI,您可以使用它来设置元素的背景。

例如,为您的 BorderPane 指定一个 fx:id

<BorderPane fx:id="bPane" fx:controller="application.PlayController" xmlns:fx="http://javafx.com/fxml"
prefHeight="200" prefWidth="320" >

然后从那里添加

@FXML
private Borderpane bPane;

到您的 Controller 类。

最后,创建方法

@FXML
public void initialize(){
    bPane.setBackground(new Background(myBI));
}

关于Javafx设置背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50509010/

相关文章:

java - Hudson 不使用 Maven 生成的类路径?

Java:创建一个后台线程来更新变量

javascript - jquery - 拉伸(stretch)背景图像以填充文档而不是窗口?

html - 我想向移动设备Opencart显示不同的背景

java - Graylog Google Pub/Sub 输出插件问题

java - 在循环中使用 Map.put(String, Integer)

javafx - 使用 JavaFX 创建气泡/语音文本样式

javafx Tableview 按日期排序

JavaFx,FXML,如何根据其 parent 自动调整内容大小: Button, StackPane,Field,Scrollpane

ios - View 上的模糊背景无法始终如一地工作