ublic class TheMedicalResourceManagementSystem
{
    JFrame jf;
    JPanel jp;
    JButton b;
    JTextField t;
    JTextField t2;

    public static void main(String[] args)
    {
        TheMedicalResourceManagementSystem cc = new TheMedicalResourceManagementSystem();

       // SwingUtilities.invokeLater(() -> new GUI("The Medical Resource Management System").setVisible(true));
    }

    public TheMedicalResourceManagementSystem()
    {



        jf = new JFrame("Frame");
        jp = new JPanel();
        jp.setLayout(new FlowLayout());
        jf.add(jp);
        t = new JTextField(15);
        jp.add(t);
           t2 = new JTextField(15);
        jp.add(t);
        jp.add(t2);

b= new JButton("Login");
jp.add(b);

        jf.setSize(200,200);
        jf.setVisible(true);

        String username = t.getText();
        String password = t2.getText();

         b.addActionListener((ActionEvent e) -> {
             if(username.equals("admin") && password.equals("password"))
             {
                 SwingUtilities.invokeLater(() -> new GUI("Medical Remote Management System").setVisible(true));
             }

             else
             {
                 JOptionPane.showMessageDialog( null, "Incorrect username or password , Please try again");
             }});

}


}


在我的程序中,我希望输入用户名和密码,输入并更正后,它应该可以正常运行。我无法运行它,因为当我输入admin和密码时,它一直告诉我用户或密码错误,即使不是这样?

最佳答案

与大多数GUI框架一样,Swing是事件驱动的。这意味着信息与收集时间有关。

在上面的示例中,您甚至在完全实现UI(呈现给用户)之前就获得了usernamepassword,因此它将仅返回文本字段的初始值(可能为空白)

相反,您需要在username时获取passwordActionEvent,因为那是与代码最相关的时间,例如...

b.addActionListener((ActionEvent e) -> {
    String username = t.getText();
    String password = t2.getText();
    if(username.equals("admin") && password.equals("password")) {
        SwingUtilities.invokeLater(() -> new GUI("Medical Remote Management System").setVisible(true));
    } else {
        JOptionPane.showMessageDialog( null, "Incorrect username or password , Please try again");
    }
});

07-24 19:55