Skip to content
Advertisement

Java bindBidirectional

I have the following problem. My task is to create a double bond between my sudoku field object and its graphical form in the GUI. So far I’ve managed to come up with something like this.

TextField textField = new TextField();

JavaBeanIntegerPropertyBuilder builder = JavaBeanIntegerPropertyBuilder.create();
JavaBeanIntegerProperty test =  builder.bean(board.getSudokuField(i,j))
        .name("FieldValue").build();
StringConverter<Number> converter = new NumberStringConverter();
Bindings.bindBidirectional(textField.textProperty(), test, converter);

The solution works, but if you enter any character other than a number, it throws a parse error.

Caused by: java.text.ParseException: Unparseable number: “a”

Is this the best way to somehow change the type of bond? Or adding a condition regarding the input values,but I just don’t know how to do it. board.getSudokuField(i,j) return SudokuField Object. And there are int getFieldValue() which return int and void setFieldValue(int value)

Advertisement

Answer

So here’s my solution, the numbers entered into the TextField can only be a number between 1 and 9.

 TextField textField = new TextField();

                JavaBeanIntegerPropertyBuilder builder =
                        JavaBeanIntegerPropertyBuilder.create();
                JavaBeanIntegerProperty test =  builder.bean(board.getSudokuField(i,j))
                        .name("FieldValue").build();
                StringConverter<Number> converter = new NumberStringConverter();

            textField.setTextFormatter(new TextFormatter<>(c -> {
                if (c.isContentChange()) {
                    if (c.getControlNewText().length() == 0) {
                        return c;
                    }

                    try {
                        Integer.parseInt(c.getControlNewText());
                        if (Integer.parseInt(c.getControlNewText()) > 9
                                || Integer.parseInt(c.getControlNewText()) == 0) {
                            return null;
                        }

                        return c;
                    } catch (NumberFormatException ignored) {
                        ignored.getMessage();
                    }
                    return null;
                }
                return c;
            }));
                Bindings.bindBidirectional(textField.textProperty(), test, converter);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement