代码之家  ›  专栏  ›  技术社区  ›  Arceus

JavaFX区域的布局问题

  •  1
  • Arceus  · 技术社区  · 8 年前

    我想编写一个新类,它扩展了包含StackPane的Region。但当我给它添加填充或边框之类的嵌入内容时,我就遇到了麻烦。下面是该类的一个简化示例:

    public class CustomPane extends Region
    {
        private ToggleButton testControl = new ToggleButton("just a test control");
        private StackPane rootPane = new StackPane(testControl);
    
        public CustomPane()
        {
            getChildren().add(rootPane);
            setStyle("-fx-border-color: #257165; -fx-border-width: 10;");
        }
    }
    

    enter image description here

    如果我试图通过调用

    rootPane.setLayoutX(10);
    rootPane.setLayoutY(10);
    

    那么该地区就会增长:

    enter image description here

    但我真的希望它看起来像这样:

    enter image description here

    (第三个图像是通过扩展StackPane而不是Region创建的,它已经正确地管理了布局内容。不幸的是,我必须扩展Region,因为我想保留 getChildren() 受保护。)

    好吧,我试着处理布局计算,但没有想到。专家能给我一些建议吗?

    1 回复  |  直到 8 年前
        1
  •  3
  •   fabian    8 年前

    StackPane 使用 insets 让(管理的)孩子下岗。 Region 默认情况下不会这样做。因此,您需要覆盖 layoutChildren 用这些东西 插图 例如:

    @Override
    protected void layoutChildren() {
        Insets insets = getInsets();
        double top = insets.getTop(),
                left = insets.getLeft(),
                width = getWidth() - left - insets.getRight(),
                height = getHeight() - top - insets.getBottom();
    
        // layout all managed children (there's only rootPane in this case)
        layoutInArea(rootPane,
                left, top, // offset of layout area
                width, height, // available size for content
                0,
                HPos.LEFT,
                VPos.TOP);
    }