#Adding Items to a ListView from a JavaFX ComboBox

5 messages · Page 1 of 1 (latest)

unique dirge
#

I have a ComboBox with multiple items. Clicking an Item will add it to the ListView window. My problem is that if I use the arrow keys to navigate the combobox, every single item I highlight when navigating gets added to the ListView. I only want the item that I click or press enter on when using the arrow keys.

` ListView<String> notesListView = new ListView<>();
notesListView.setPrefHeight(95);

    notesListView.setCellFactory(lv -> {
        ListCell<String> cell = new ListCell<>();

        HBox hbox = new HBox();
        hbox.setFillHeight(true);
        hbox.setPrefWidth(1);
        HBox.setHgrow(hbox, Priority.ALWAYS);

        Label label = new Label();
        Pane pane = new Pane();
        Button deleteButton = new Button("X");

        deleteButton.setStyle("-fx-text-fill: red; -fx-font-weight: bold;");

        deleteButton.setOnAction(e -> {
            notesListView.getItems().remove(cell.getItem());
        });

        HBox.setHgrow(pane, Priority.ALWAYS);

        hbox.getChildren().addAll(label, pane, deleteButton);
        hbox.setAlignment(Pos.CENTER_LEFT);

        cell.itemProperty().addListener((obs, oldItem, newItem) -> {
            if (newItem == null) {
                cell.setGraphic(null);
            } else {
                label.setText(newItem);
                cell.setGraphic(hbox);
            }
        });
        return cell;
    });
    
    // Add selected item to the list
    noteValueCombo.getSelectionModel().selectedItemProperty().addListener((options, oldValue, newValue) -> {
        if (newValue != null && !notesListView.getItems().contains(newValue)) {
            notesListView.getItems().add(newValue);
        }
    });`
weak condorBOT
#

This post has been reserved for your question.

Hey @unique dirge! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

weak condorBOT
#

💤 Post marked as dormant

This post has been inactive for over 300 minutes, thus, it has been archived.
If your question was not answered yet, feel free to re-open this post or create a new one.

unique dirge
#

Any help with this?