How to regenerate indexes after removing element

282 views Asked by At

I am having simple vbox which will have six hboxes and I can delete one/all and add once again.

My code :

@FXML
private VBox userSelectedValues;

int index = userSelectedValues.getChildren().indexOf(event.getSource()); 

userSelectedValues.getChildren().remove(cnt);
ObservableList<Node> hboxNodes = FXCollections.observableArrayList();
hboxNodes.addAll(userSelectedValues.getChildren());
userSelectedValues.getChildren().clear();
userSelectedValues.getChildren().addAll(hboxNodes);

Scenario : there are six elements initially

1) I deleted 4th element - works fine - now total 5 elements
2) I deleted 3rd element - works fine - now total 4 elements
3) Now if I want to delete 6th element is giving me the indexOutOfBoutnd which is expected.

So how to regenerate or refresh indexes.

Thank you,

1

There are 1 answers

2
Roland On

What do you mean with "refresh" indexes? The children are in an ObservableList. If you remove an item, then the indexes change.

Example:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {

        HBox root = new HBox();

        Label label1 = new Label( "Label1");
        Label label2 = new Label( "Label2");
        Label label3 = new Label( "Label3");

        root.getChildren().addAll( label1, label2, label3);

        System.out.println( "Original:");

        System.out.println(label1.getText() + ": " + root.getChildren().indexOf(label1));
        System.out.println(label2.getText() + ": " + root.getChildren().indexOf(label2));
        System.out.println(label3.getText() + ": " + root.getChildren().indexOf(label3));


        root.getChildren().remove(label2);

        System.out.println( "Modified:");

        System.out.println(label1.getText() + ": " + root.getChildren().indexOf(label1));
        System.out.println(label2.getText() + ": " + root.getChildren().indexOf(label2));
        System.out.println(label3.getText() + ": " + root.getChildren().indexOf(label3));


        Scene scene = new Scene(root, 800, 600);
        primaryStage.setScene(scene);
        primaryStage.show();

    }

    public static void main(String[] args) {
        launch(args);
    }
}

The 2nd item is removed, the console output is as expected:

Original:
Label1: 0
Label2: 1
Label3: 2

Modified:
Label1: 0
Label2: -1
Label3: 1

According to the documentation about indexOf:

Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.