0

I'm new to JavaFX, I'm getting this weird exception whenever I select an item from ComboBox, I have a bunch of records in the database that I'm fetching and putting in the combo box as String, the thing is when I select the items in the Combobox I get ArrayIndexOutOfBoundsException: -1, sometimes I can display the information needed from the ComboBox and sometimes I can't, what is causing this error? and how can I fix it, help will be appreciated?

Here is the ComboBox action method:

@FXML
private ComboBox<String> recherche;

@FXML
private void Combo(ActionEvent event) {
        Platform.runLater(() -> {

            int selectedIndex = this.recherche.getSelectionModel().getSelectedIndex();
            System.out.println("**************selected intedx "+selectedIndex); //prints -1 and throws ArrayOutOfBoundsException

            ObservableList<String> listPayment = FXCollections
                    .observableArrayList(PaymentQueries.listOfPayamentDates(listOfData);
            recherche.setItems(listPayment);
            recherche.setEditable(true);
            //for autocompletion
            TextFields.bindAutoCompletion(recherche.getEditor(), recherche.getItems());

        });

    }

I call this method before I show the Combobox:

 public void reload() {
        Platform.runLater(() -> {

            clearFields();
            ObservableList<String> listEnfant = FXCollections.observableArrayList(EnfantQueries.getData().getNoms());
            recherche.setItems(listEnfant);
            recherche.setEditable(true);
            TextFields.bindAutoCompletion(recherche.getEditor(), recherche.getItems());
        });

    }
Nicolai Parlog
  • 47,972
  • 24
  • 125
  • 255
Gherbi Hicham
  • 2,416
  • 4
  • 26
  • 41
  • Can you show us the initialization of the recherche items? I mean where do you call the setItems() first time? If the answer is inside the Combo method then the reason you are taking -1 for the selectedIndex is because you have no items inside. create the @FXML public void initialize() method and set the items to combobox – JKostikiadis Sep 30 '17 at 09:56
  • No, I'm using a menuBar so each time I click a menu item I call setItems() on my recherche comboBox, also I'm getting all the items I expect in the comboBox, so it's not about not getting the items, everything works eccept for when I actually select an Item, I'm using a reload method when I click on teh menu Item, I added it to the code – Gherbi Hicham Sep 30 '17 at 10:09
  • hmm with an error ArrayIndexOutOfBoundsException + you are saying that you can view all the items on the combobox ( at least until you select one ) I can only assume that you somehow remove the items before you can actually can take the selected one or you set the selectedItem = -1 somehow. To be sure please print the recherche.getItem().size() before you print the selectedIndex if it's 0 then you need to find what's wrong about the data insertion. If it's not there search if you are setting somewhere the selectedIndex = -1 – JKostikiadis Sep 30 '17 at 10:18
  • If you can post a working example of your problem I could help you fast ;) cause I will be able to see the whole picture. Cause now for example I can't see if there is something wrong inside 'clearFields()' etc. – JKostikiadis Sep 30 '17 at 10:20
  • The selected index being -1 just means nothing is selected, which I think happens when you reset the combo box's items list. So this is probably an expected value which you should check for. – James_D Sep 30 '17 at 11:47
  • 1
    Aside: why do you have the `Platform.runLater(...)` in what appear to be event handlers? – James_D Sep 30 '17 at 11:48
  • -1 means that any elements is selected ,but i think your comboBox has not any items ,before you select an item ,move first two lines after pushing your items in comboBox. – Menai Ala Eddine - Aladdin Sep 30 '17 at 13:26

1 Answers1

1

As this is a common symptom with many causes, it may help to examine it in isolation. Starting from the example seen here, the variation below listens to the combo's SelectionModel and displays the value of the current selection in a TextField. Note that the combo's selected index becomes -1 when the Clear button is used to clear the combo's model.

SingleSelectionModel selectionModel = comboBox.getSelectionModel();
TextField selection = new TextField(String.valueOf(selectionModel.getSelectedIndex()));
selectionModel.selectedIndexProperty().addListener((Observable o) -> {
    selection.setText(String.valueOf(selectionModel.getSelectedIndex()));
});
…
dialogPane.setContent(new VBox(8, textField, datePicker, comboBox, selection, …));

image

Complete example:

import java.time.LocalDate;
import java.util.Optional;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.Observable;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Dialog;
import javafx.scene.control.DialogPane;
import javafx.scene.control.SingleSelectionModel;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 * @see https://stackoverflow.com/a/46504588/230513
 * @see http://stackoverflow.com/q/44147595/230513
 * @see http://www.javaworld.com/article/2991463/
 */
public class DialogTest extends Application {

    @Override
    public void start(Stage primaryStage) {
        Dialog<Results> dialog = new Dialog<>();
        dialog.setTitle("Dialog Test");
        dialog.setHeaderText("Please specify…");
        DialogPane dialogPane = dialog.getDialogPane();
        dialogPane.getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);
        TextField textField = new TextField("Name");
        DatePicker datePicker = new DatePicker(LocalDate.now());
        ObservableList<Venue> options =
            FXCollections.observableArrayList(Venue.values());
        ComboBox<Venue> comboBox = new ComboBox<>(options);
        SingleSelectionModel selectionModel = comboBox.getSelectionModel();
        selectionModel.selectFirst();
        TextField selection = new TextField(String.valueOf(selectionModel.getSelectedIndex()));
        selectionModel.selectedIndexProperty().addListener((Observable o) -> {
            selection.setText(String.valueOf(selectionModel.getSelectedIndex()));
        });
        Button clear = new Button("Clear");
        clear.setOnAction((action) -> {
            options.clear();
        });
        Button restore = new Button("Restore");
        restore.setOnAction((action) -> {
            options.clear();
            options.addAll(Venue.values());
            selectionModel.selectLast();
        });
        dialogPane.setContent(new VBox(8, textField, datePicker, comboBox, selection, clear, restore));
        Platform.runLater(textField::requestFocus);
        dialog.setResultConverter((ButtonType button) -> {
            if (button == ButtonType.OK) {
                return new Results(textField.getText(),
                    datePicker.getValue(), comboBox.getValue());
            }
            return null;
        });
        Optional<Results> optionalResult = dialog.showAndWait();
        optionalResult.ifPresent((Results results) -> {
            System.out.println(
                results.text + " " + results.date + " " + results.venue);
        });
    }

    private static enum Venue {Here, There, Elsewhere}

    private static class Results {

        String text;
        LocalDate date;
        Venue venue;

        public Results(String name, LocalDate date, Venue venue) {
            this.text = name;
            this.date = date;
            this.venue = venue;
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}
trashgod
  • 203,806
  • 29
  • 246
  • 1,045