MVC Java Swing 如何从视图中正确获取数据库中的数据

MVC Java Swing how to correctly get data from database from a view

我正在按照 MVC 设计模式编写一个简单的 Java Swing GUI 应用程序。我有一个 MainFrame.java 实例化 LoginDialog.java (模态 JDialog)。然后用户使用用户名和密码登录,或者可以注册(通过单击 Jbutton)实例化 RegisterDialog.java(JDialog 从 LoginDialog 实例化)。我还有一个 Controller.java class 连接到 Database.java,并允许与数据库交互。 MainFrame 对象可以通过控制器对象与数据库进行交互。在 RegisterDialog 上,当用户按下提交时,我想验证用户名是否尚未被使用。如何从 RegisterDialog 的数据库中获取数据?另外,我如何从 LoginDialog 获取数据(我应该让 MainFrame 监听从 LoginDialog 触发的 DataRequestEvent 吗?)

public class Controller {
    private Database db;
    public Controller(){
    db = new Database();
    }
}
public class MainFrame extends JFrame{
    private LoginDialog loginDialog;
    private Controller controller;
    public MainFrame(){
        controller = new Controller();
        loginDialog = new LoginDialog();
        loginDialog.setVisible(true);
        //...
    }
}
public class LoginDialog extends JDialog{
    //form fields...
    private JButton regBtn;
    private RegisterDialog registerDialog;
    public LoginDialog(){
        registerDialog = new RegisterDialog();
        regBtn = new JButton("Register");
        regBtn.addActionListener(new ActionListener(){
            registerDialog.setVisible(true);
        });
    }
}

public class RegisterDialog extends JDialog{
    //...
    private JButton submitBtn;
    public RegisterDialog(){
        submitBtn = new JButton();
        submitBtn.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                validateUsername();
            }
        });
    }
    public void validateUsername(){
        //here I need to check whether username is already in DB (sqlite)
    }       
}

正如所讨论的 here, "not every interaction needs to pass through your application's controller," but authentication and registration are reasonable candidates for your controller to manage. As outlined here, your controller may manipulate your data model directly, and listening views should update themselves accordingly. As shown here, Swing provides a number of ways to implement the observer pattern in order to handle such notifications. The exact details depend on how your application handles modality, but your authentication and registration dialogs can fire a suitable PropertyChangeEvent to notify listeners as needed. Examples may be found here and here