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

JavaFX如何获取特定Pane尺寸并监听窗口resize时的尺寸变化

跟踪嵌套AnchorPane的尺寸变化

没问题,这个需求其实很容易实现——AnchorPane本身就提供了和Scene一样的widthProperty()和heightProperty(),不管它嵌套多少层父容器,只要布局约束设置正确,窗口调整时这些属性就会自动更新,直接给它们加监听器就行。

核心实现代码

先拿到你的目标AnchorPane实例(不管是代码创建还是FXML注入的),然后给它的宽高属性添加监听器,写法和Scene的监听器几乎一致:

// 假设你的AnchorPane实例名为targetAnchorPane
targetAnchorPane.widthProperty().addListener((observable, oldWidth, newWidth) -> {
    int updatedWidth = newWidth.intValue();
    System.out.println("AnchorPane当前宽度: " + updatedWidth);
});

targetAnchorPane.heightProperty().addListener((observable, oldHeight, newHeight) -> {
    int updatedHeight = newHeight.intValue();
    System.out.println("AnchorPane当前高度: " + updatedHeight);
});

关键注意事项

要确保你的AnchorPane能跟随窗口缩放,必须给它设置正确的布局约束:

  • 如果是代码创建的AnchorPane,记得绑定父容器的四边:
    AnchorPane.setTopAnchor(targetAnchorPane, 0.0);
    AnchorPane.setBottomAnchor(targetAnchorPane, 0.0);
    AnchorPane.setLeftAnchor(targetAnchorPane, 0.0);
    AnchorPane.setRightAnchor(targetAnchorPane, 0.0);
    
  • 如果是FXML里定义的,要在标签里加上对应的约束:
    <AnchorPane fx:id="targetAnchorPane" AnchorPane.topAnchor="0.0" AnchorPane.bottomAnchor="0.0"
                AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0">
        <!-- 子控件内容 -->
    </AnchorPane>
    

要是没设置这些约束,AnchorPane的大小可能会固定,监听器就不会触发啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:24:25