JavaFX在另一个节点(XML)之后或之前添加节点(program)

JavaFX在另一个节点(XML)之后或之前添加节点(program),java,javafx,Java,Javafx,如果我像这样附加一个节点: HBox child = new HBox(); HBox fooBar = (HBox) doc.lookup("#fooBar"); fooBar.getChildren().add(child); 它可能会工作,但不是我想要的方式,因为我想定义位置。如果我想要孩子在fooBar之前或之后呢 <HBox> <HBox id="first"></HBox> <HBox id="fooBar"></HB

如果我像这样附加一个节点:

HBox child = new HBox();
HBox fooBar = (HBox) doc.lookup("#fooBar");

fooBar.getChildren().add(child);
它可能会工作,但不是我想要的方式,因为我想定义位置。如果我想要孩子在fooBar之前或之后呢

<HBox>
  <HBox id="first"></HBox>
  <HBox id="fooBar"></HBox>
  <HBox id="last"></HBox>
</HBox>

fooBar.getParent().getChildren()
返回一个
可观察列表
,当它从
java.util.List
继承时,它有一个方法
add(int index,E元素)
(中的进一步信息)

将新节点添加到正确的位置就可以了。 下面的代码将子项添加到fooBar之前

int fooBarIndex = fooBar.getParent().getChildren().indexOf(fooBar);
fooBar.getParent().getChildren().add(fooBarIndex, child)
fooBar.getParent().getChildren()
返回一个
ObservableList
,该列表继承自
java.util.List
,具有一个方法
add(int index,E元素)
(中的进一步信息)

将新节点添加到正确的位置就可以了。 下面的代码将子项添加到fooBar之前

int fooBarIndex = fooBar.getParent().getChildren().indexOf(fooBar);
fooBar.getParent().getChildren().add(fooBarIndex, child)

当然,
fooBar.getChildren().indexOf(fooBar)
必然会返回
-1
,因为不允许将节点作为其自身的子节点添加,但这是问题多于答案的问题。谢谢!这太好了。当然,
fooBar.getChildren().indexOf(fooBar)
必然会返回
-1
,因为不允许将节点作为其自身的子节点添加,但这是问题多于答案的问题。谢谢!那太好了。