[英]JavaFX data binding with fxml fields
I have created a fxml file for LoginForm and a controller and model. 我已经为LoginForm和控制器和模型创建了一个fxml文件。 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.
我尝试将模型与fxml视图绑定,以使其可以显示在TextField上,并且可以获取输入值,例如Spring MVC。 Using below code, data shown on TextField but I am not able to change value on UI.
使用下面的代码,数据显示在TextField上,但我无法更改UI上的值。
How to make editable TextField with text
attribute? 如何使具有
text
属性的可编辑TextField? Or I can say how to bind TextField with java Model to send input data to controller. 或者我可以说如何将TextField与Java Model绑定以将输入数据发送到控制器。
fxml code: fxml代码:
<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: Java代码:
@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. 在控制器中,我总是将null作为用户名和密码。
Binding the Node
s' properties is most likely the wrong approach here. 绑定
Node
的属性很可能是错误的方法。 The information should be taken from the UI and put into the LoginModel
instead of the other way round. 该信息应从UI中获取,并放入
LoginModel
而不是反过来。 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. 此外,您很可能希望等待用户单击某些按钮或按Enter键提交数据,而不是每次用户在
TextField
之一中键入字母时都这样做。
You probably want your BeanFactory
to create the LoginModel
for you instead of using the FXMLLoader
to create it. 您可能希望
BeanFactory
为您创建LoginModel
,而不是使用FXMLLoader
来创建它。
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");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.