简体   繁体   中英

Real-time JavaFX-8 Form Management

Alright, here's my dilemma. I'm trying to create a JavaFX Form with TextFields and other elements. But for right now, I need to know how to implement a form that fills in realtime.

Theoretically, for example let's say I have two TextFields.

TextField textfield1 = new TextField();
TextField textfield2 = new TextField();

The second textfield depends on whatever value was entered in the first textfield. As soon as the user has finished typing on the first, the second is then populated with a value.

if(!textfield.getText().equals("")) {
    textfield2.setText("blah, blah, blah");
}

For a real case example, let's say that I was making a payroll system. The user types in the employee's basic pay (in the first textfield), as soon as that's done the value for the employee's monthly salary: basic pay * 2, is entered (in the second textfield).

The second is non-editable, only the first one is. Pretty sure that I need some kind of event handler on the first field, but I really am stumped on how or what code to write. I am new to JavaFX by the way. Any help would be appreciated.

UPDATE : I'm using Scenebuilder on this (sorry I forgot to include that). Because of that each elements' listeners are grouped into defined functions in the controller. It feels weird to me using inner classes ever since I scrapped Swing (and Windowbuilder), using Eclipse by the way. I'd like to keep the code convention consistent all across the board.

I believe you're asking how to implement a focus lost listener. This demonstrates how you can add a change listener to the focusProperty() of the first text field and use it to trigger an update of the second.

This can be done within the controller by placing logic inside the an @FXML annotated initialize() method. This is called automagically by JavaFX after all the @FXML annotated fields have been injected.

public class Controller {
    @FXML
    private TextField textfield1;
    @FXML
    private TextField textfield2;

    @FXML
    public void initialize() {
        textfield1.focusedProperty().addListener((obs, oldValue, newValue) -> {
            if (!newValue) { // focus lost
                if (!"".equals(textfield1.getText())) {
                    textfield2.setText("blah, blah, blah");
                } else {
                    textfield2.setText("");
                }
            }
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM