You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在FXML中为JavaFX BorderPane设置背景(不使用CSS)

嘿,我来帮你搞定BorderPane设置背景的问题!你思路是对的,确实需要用borderPane.setBackground(new Background(myBI)),但现在的问题是你还没在Controller里拿到BorderPane的引用,而且有些细节没处理好,我一步步给你改:

问题核心

你当前的Controller里没有关联FXML中的BorderPane,而且BackgroundImage不该加@FXML注解(这个注解是用来注入FXML里定义的元素的,不是代码里创建的对象),另外设置背景的操作得等FXML元素都加载完成后再执行。

修改步骤及代码

1. 给FXML里的BorderPane添加fx:id

这样Controller才能拿到它的引用,修改后的FXML代码:

<BorderPane fx:controller="application.PlayController" xmlns:fx="http://javafx.com/fxml" prefHeight="200" prefWidth="320" fx:id="mainBorderPane">
    <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>

2. 调整Controller代码

注入BorderPane,去掉BackgroundImage的@FXML,并通过Initializable接口的初始化方法设置背景:

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundImage;
import javafx.scene.layout.BackgroundPosition;
import javafx.scene.layout.BackgroundRepeat;
import javafx.scene.layout.BackgroundSize;
import javafx.scene.image.Image;
import javafx.event.ActionEvent;
import java.net.URL;
import java.util.ResourceBundle;

public class PlayController implements Initializable {
    @FXML
    private Label label;
    @FXML
    private TextField textfield;
    @FXML
    private BorderPane mainBorderPane; // 注入FXML中的BorderPane

    // 这里不需要@FXML,这是我们代码里创建的背景图对象
    private BackgroundImage myBI = new BackgroundImage(
            new Image("/Background.png", 1280, 720, false, true),
            BackgroundRepeat.REPEAT, BackgroundRepeat.NO_REPEAT,
            BackgroundPosition.DEFAULT, BackgroundSize.DEFAULT
    );

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        // 初始化方法会在所有FXML元素加载完成后执行,这里设置背景不会空指针
        mainBorderPane.setBackground(new Background(myBI));
    }

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

关键注意点

  • 确保你的Background.png路径正确:如果是放在项目的资源根目录(比如Maven的src/main/resources),用/Background.png是正确的,它会从类路径根目录查找图片。
  • 一定要在initialize方法里设置背景,因为这时候FXML里的BorderPane已经被实例化好了,直接在Controller构造方法里设置会导致空指针异常。

内容的提问来源于stack exchange,提问作者Eric mansen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:06:35