Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8115423

ListView selectionModel selectedItems list returns incorrect size

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Fixed
    • Icon: P4 P4
    • 8
    • 7u6
    • javafx

      I just stumbled over an error in my ListView and found out, that the selectionModel.getSelectedItems().size() is always 1, if I selected an item, and then clear all items (or remove the selected one).

      This is confusing, at least for me. I expected the size() to be 0, as it is the same state as before, if nothing was selected.

      Code sample: Add 2 items, select the FIRST one, click the clear button. getSelectedItems().size() is 1 then. Strangely, if you selected the second item, the size() is 0.

      import javafx.application.Application;
      import javafx.collections.FXCollections;
      import javafx.collections.ObservableList;
      import javafx.event.ActionEvent;
      import javafx.event.EventHandler;
      import javafx.scene.Scene;
      import javafx.scene.control.Button;
      import javafx.scene.control.ListView;
      import javafx.scene.layout.VBoxBuilder;
      import javafx.stage.Stage;

      public class TestApp2 extends Application {
          public static void main(String[] args) {
              Application.launch();
          }


          private ObservableList<String> items = FXCollections.observableArrayList();

          @Override
          public void start(Stage stage) throws Exception {
              final ListView<String> listView = new ListView<String>();
              listView.setItems(items);

              System.out.println(listView.getSelectionModel().getSelectedItems().size());
              Button buttonAdd = new Button("Add");
              buttonAdd.setOnAction(new EventHandler<ActionEvent>() {
                  @Override
                  public void handle(ActionEvent actionEvent) {
                      items.add("Test");
                  }
              });
              Button buttonClear = new Button("Clear");
              buttonClear.setOnAction(new EventHandler<ActionEvent>() {
                  @Override
                  public void handle(ActionEvent actionEvent) {
                      items.clear();
                      System.out.println(listView.getSelectionModel().getSelectedItems().size());
                  }
              });

              Scene scene = new Scene(VBoxBuilder.create().children(listView, buttonAdd, buttonClear).build());
              stage.setScene(scene);
              stage.show();
          }
      }

            jgiles Jonathan Giles
            cschudtjfx Christian Schudt (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported: