java - JTextField 和 JButton 登录页面

标签 java swing

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");
             }});

}


}

在我的程序中,我希望输入用户名和密码,当输入并正确时,它应该运行所有内容。我无法让它运行,因为当我输入管理员和密码时,它一直告诉我用户或密码错误,即使它不是?

最佳答案

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

在上面的示例中,您甚至在 UI 完全实现(呈现给用户)之前就获取了用户名密码,因此它只会返回初始值文本字段的值(可能为空)

相反,您需要在 ActionEvent 发生时获取用户名密码,因为此时它与代码最相关,例如...

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");
    }
});

关于java - JTextField 和 JButton 登录页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47641926/

相关文章:

java - 我的 java 程序没有正确计算数据库行数

java - 还有什么工具可以替代 Selenium?

java - 保持敏锐的 GUI 开发技能

java - 关闭程序时运行方法?

java - Sockets 和 ServerSockets 服务器/客户端 GUI 聊天程序

java - 404错误的解决方法 使用带有json的restful web services

java - 使用 Jackson 将嵌套数组反序列化为 ArrayList

java - Jpanel 元素尺寸过大

java - Eclipse 风格的选项卡式 Pane ——选项卡太多时的 "Show List"按钮

java - 为什么ObjectMapper将Date类型改为Long