2017-10-20 78 views
0

鉴于以下布局:JavaFX的:布图中的节点的行

enter image description here

在一些情况下字段2(和上面的相应Label)是不可见的和字段3字段4应相应地向左移动。

我的第一个尝试是将元素放置在Pane(因为我也是这个例子中的屏幕截图),并重新计算所有元素的确切位置,如果一个元素被设置为不可见的话。此解决方案正在运行,但如果元素,其大小或顺序发生更改,则需要大量维护。

在讨论另一个问题的过程中,我得到了使用HBox来放置字段的想法,这会给我自动间隔。

但使用HBox不会做的伎俩,因为:

  1. 至于我在HBox看到标签不能元素以上进行设置。
  2. 如果我设置一个元素不可见,其他元素不会左移。

任何想法如何将我想要的行为存档?

回答

2

将每个LabelComboBox/Label代入VBox。然后根据您的要求将它们从HBox中添加/删除。另一种解决方案是将所有内容都放入GridPane并添加/删除列。

+2

如果你喜欢使用'调用setVisible()'代替添加和去除'VBox',只是结合'VBox'” s'managedProperty()'到它的'visibleProperty()'。 –

2

使Node隐形不会将其从版面中删除。删除从父布局的节点由

  1. 从父
  2. 节点的managed属性设置为false的孩子列表中移除一个Node完成。

实施例示出/使用managed属性隐藏节点:

public static void toggleVisibility(Node node) { 
    boolean newValue = !node.isVisible(); 
    node.setVisible(newValue); 

    // invisible nodes should not be taken into account for HBox layout 
    node.setManaged(newValue); 
} 

@Override 
public void start(Stage primaryStage) { 
    Rectangle rect1 = new Rectangle(100, 100, Color.RED.deriveColor(0, 1, 1, 0.5)); 
    Rectangle rect2 = new Rectangle(100, 100, Color.GREEN.deriveColor(0, 1, 1, 0.5)); 
    Rectangle rect3 = new Rectangle(100, 100, Color.BLUE.deriveColor(0, 1, 1, 0.5)); 
    HBox hbox = new HBox(rect1, rect2, rect3); 

    Scene scene = new Scene(hbox); 
    scene.setOnMouseClicked(evt -> { 
     toggleVisibility(rect2); 
    }); 

    primaryStage.setScene(scene); 
    primaryStage.show(); 
}