Editable TableView in JavaFX, numeric only input

Viewed 2191

I am trying to create an editable TableView in JavaFX, displaying various values stored in a custom class InventoryLocation. Some of these values are strings, while others are various numeric data types (short, int, double), and some of the strings have specific required formats associated with them. I am using something like the following block of code to define each table column, using SortStringConverter() or similar to take the text input and convert it to the target datatype:

    TableColumn<InventoryLocation,Short> CabinetColumn = new TableColumn<>("Cabinet");
    CabinetColumn.setMinWidth(50);
    CabinetColumn.setCellValueFactory(new PropertyValueFactory<>("Cabinet"));
    CabinetColumn.setCellFactory(TextFieldTableCell.forTableColumn(new ShortStringConverter()));

However, I would like to prevent the user from entering any invalid data to begin with. For the above example, they should not be able to type any non-numeric characters. Elsewhere in my application, in simple TextFields, I am using something like this to enforce Regex matching on the user input:

    quantity.textProperty().addListener(new ChangeListener<String>() {
        @Override
        public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
            if (!newValue.matches("\\d*")) {
                quantity.setText(newValue.replaceAll("[^\\d]", ""));
            }
        }
    });

How can I apply something similar to the text entry used by an editable TableView? Currently, the first code block will allow the user to write any value they like, and throws a number format exception if the string cannot be converted to a short. I would like the code to prevent them from entering invalid values in the first place.

1 Answers
Related