JavaFX VBox和HBox布局

时间:2013-03-08 20:43:51

标签: layout javafx-2

我正在研究JavaFX应用程序,该应用程序具有从外部数据结构生成的布局,由

组成
  • 显示知道其自身纵横比(高度取决于宽度)的组件
  • 2种结构组件
    • 在页面上显示所有宽度相等的孩子,每个孩子都需要尽可能多的垂直空间
    • 使用全宽显示所有孩子,并根据需要占用尽可能多的垂直空间

但我发现事情并没有像我期望的那样显示出来。我做了一个简化的案例来证明这个问题。

代码如下,问题是v3没有显示,我不能为我的生活找出原因。我想有VBox es和HBox es的一些方面,我还没有理解。

我真的很感激任何帮助或想法。提前谢谢!

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

import java.util.Random;

public class Test extends Application {

    static Random rand = new Random();

    public static void main(String args[]) {
        Application.launch("something");
    }

    @Override
    public void start(Stage mainStage) throws Exception {
        testVBoxes(mainStage);
    }

    private void testVBoxes(Stage mainStage) {
        VBox root = new VBox();
        Scene one = new Scene(root, 800, 600, Color.WHITE);

        FixedAspectRatioH h1 = new FixedAspectRatioH();
        FixedAspectRatioH h2 = new FixedAspectRatioH();
        FixedAspectRatioH h3 = new FixedAspectRatioH();
        FixedAspectRatioV v1 = new FixedAspectRatioV();
        FixedAspectRatioV v2 = new FixedAspectRatioV();
        FixedAspectRatioV v3 = new FixedAspectRatioV();

        h1.prefWidthProperty().bind(root.widthProperty());

        h2.add(v2);

        v1.add(h3);
        v1.add(h2);

        h1.add(v1);
        h1.add(v3);

        root.getChildren().add(h1);

        mainStage.setScene(one);
        mainStage.show();
    }

    private class FixedAspectRatioV extends VBox {
        public FixedAspectRatioV() {
            Rectangle r = new Rectangle();
            r.setFill(Color.rgb(rand.nextInt(256), rand.nextInt(256),     rand.nextInt(256)));
            r.widthProperty().bind(widthProperty());
            r.heightProperty().bind(r.widthProperty().divide(3));
            getChildren().add(r);
        }

        public void add(Region n) {
            n.prefWidthProperty().bind(widthProperty());
            getChildren().add(n);
        }
    }

    private class FixedAspectRatioH extends HBox {
        public FixedAspectRatioH() {
            Rectangle r = new Rectangle();
            r.setFill(Color.rgb(rand.nextInt(256), rand.nextInt(256),     rand.nextInt(256)));
            r.widthProperty().bind(widthProperty().divide(4));
            r.heightProperty().bind(r.widthProperty());
            getChildren().add(r);
        }

        public void add(Region n) {
            HBox.setHgrow(n, Priority.ALWAYS);
            getChildren().add(n);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

它的2年但解决方案是你忘了

Node.setPrefSize(width,height);

并将其添加到构造函数Hbox.setFillHeight(true);