averageCoder
averageCoder

Reputation: 3

How can I swap the order of the children in an HBox with a button in JavaFX?

If you had an HBox like this: HBox hbox = new HBox(image1, image2);

How would you swap image1 and image2 with a button click so that image2 comes before image1?

Upvotes: 0

Views: 440

Answers (1)

fabian
fabian

Reputation: 82461

If those are the only 2 children, you can use toFront on the first one

hbox.getChildren().get(0).toFront();

If they are not the only children you need to modify the list in a way that guarantees that none of the nodes is present in the list at the same time more than once:

List<Node> children = hbox.getChildren();
int index1 = children.indexOf(image1);
int index2 = children.indexOf(image2);

//get indices in order
if (index1 > index2) {
    int temp = index1;
    index1 = index2;
    index2 = temp;
}

Node n = children.remove(index2);
n = children.set(index1, n);
children.add(index2, n);

Upvotes: 2

Related Questions