Java FX MVVM架构 构建 登录界面
立即下载
资源介绍:
使用MVVM架构实现简易的登录界面
业务逻辑代码单独抽离抽离出来,
view与ViewModel进行数据绑定
控制器调用业务逻辑代码进行相应。
package com.example.mvvm;
import com.example.mvvm.model.LoginManager;
import com.example.mvvm.model.LoginResult;
import com.example.mvvm.model.UserView;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TextField;
import java.net.URL;
import java.util.ResourceBundle;
import static javafx.scene.control.Alert.AlertType.*;
public class LoginController implements Initializable {
@FXML
private TextField nameTxt;
@FXML
private TextField pwdTxt;
private final UserView userView = new UserView();
private final LoginManager loginManager = new LoginManager();
@FXML
public void cancel(ActionEvent actionEvent) {
if (userView.getName() != null || userView.getPassword() != null) {
userView.setName("");
userView.setPassword("");
nameTxt.requestFocus();
}
}
@FXML
public void login(ActionEvent actionEvent) {
if (userView.getName().trim().length()>0 && userView.getPassword().trim().length()>0) {
LoginResult result = loginManager.login(userView.getName(), userView.getPassword());
if(result == LoginResult.SUCCESS){
new Alert(INFORMATION,result.toString()).show();
}
else {
new Alert(WARNING,result.toString()).show();
}
}else {
new Alert(ERROR,"用户名或密码不能为空", ButtonType.OK).show();
}
}
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
//将userView中的属性绑定到对应的文本框
nameTxt.textProperty().bindBidirectional(userView.nameProperty());
pwdTxt.textProperty().bindBidirectional(userView.passwordProperty());
}
}