简体   繁体   中英

JavaFX data binding with fxml fields

I have created a fxml file for LoginForm and a controller and model. I tried to bind model with fxml view so that it could shown on TextField and I can get back input values, like Spring MVC. Using below code, data shown on TextField but I am not able to change value on UI.

How to make editable TextField with text attribute? Or I can say how to bind TextField with java Model to send input data to controller.

fxml code:

<fx:define>
<LoginModel fx:id="loginModel" />
</fx:define>
<Label text="Username" />
<TextField fx:id="username" GridPane.columnIndex="1" text="${loginModel.username}" editable="true" />
<Label text="Password" GridPane.rowIndex="1" />
<PasswordField fx:id="password" GridPane.columnIndex="1" GridPane.rowIndex="1" text="${loginModel.password}" />

Java Code:

@Component
public class LoginController {

@FXML
private LoginModel loginModel;

@FXML
private TextField username;

@FXML
private PasswordField password;

public void login() {
    System.out.println("loginModel = " + loginModel);
    System.out.println("On login action");
}
}

In controller I always get null as username and password.

Binding the Node s' properties is most likely the wrong approach here. The information should be taken from the UI and put into the LoginModel instead of the other way round. Furthermore you most likely want to wait for the user to click some button or press enter to submit the data instead of doing this every time the user types a letter in one of the TextField s.

You probably want your BeanFactory to create the LoginModel for you instead of using the FXMLLoader to create it.

final BeanFactory factory = ...
FXMLLoader loader = new FXMLLoader(url);
loader.setControllerFactory(cl -> {
    try {
        // use spring to create bean
        return factory.getBean(cl);
    } catch (NoSuchBeanDefinitionException ex) {
        // try create non-bean
        try {
            return cl.newInstance();
        } catch(InstantiationException | IllegalAccessException innerEx) {
            throw new RuntimeException(innerEx);
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
});
Parent p = loader.load();
@Component
@Scope("prototype")
public class LoginController {

    @Autowired
    private LoginModel loginModel;

    @FXML
    private TextField username;

    @FXML
    private PasswordField password;

    @FXML
    private void login() {
        loginModel.login(username.getText(), password.getText());
        System.out.println("On login action");
    }

}

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