fwackk
fwackk

Reputation: 97

JavaFX - How to check user input in editable TableView

I am wanting to check that the user has entered an integer, if a string is entered or the field is blank I want to display an error.

I am currently getting a NumberFormatException when entering a string in the console but cannot figure out where to add a try catch to.

This is an example of one of my columns, the others follow the same style:

regularityColumn.setMinWidth(130);
      regularityColumn.setCellValueFactory(new PropertyValueFactory<>
              ("taskTypeRegularity"));
table.getColumns().addAll(....., regularityColumn);

If a manager user is found the table is set to editable along with the following:

regularityColumn.setCellFactory(TextFieldTableCell.forTableColumn(
                new IntegerStringConverter()));
    regularityColumn.setOnEditCommit(e -> {
        TaskType selectedTask = table.getSelectionModel()
                    .getSelectedItem();
        selectedTask.setTaskTypeRegularityInt(e.getNewValue());
});

Upvotes: 1

Views: 226

Answers (1)

Jose Martinez
Jose Martinez

Reputation: 11992

Create your own StringConverter. The exception is coming from the IntegerStringConverter.

So replace this...

regularityColumn.setCellFactory(TextFieldTableCell.forTableColumn(
            new IntegerStringConverter()));

with something like this...

regularityColumn.setCellFactory(TextFieldTableCell.forTableColumn(
            new StringConverter<Integer>(){
            Integer fromString(String s) {
                 //convert the string to integer yourself and catch the exception
            }

            String toString(Integer i) {
                 //convert the integer to String yourself and catch the exception
            }
        }
    )
);

Please note I typed the code without an IDE, so excuse any typos. If you will use this in multiple places, then turn it into its own class that can be re-used, e.g. MyIntegerStringConverter.

Upvotes: 1

Related Questions