JPanel .getText();问题

时间:2017-12-29 08:53:37

标签: java jpanel

我正在尝试验证用户输入是否等于字符串集。它似乎不像.getText();将用户输入设置为字符串值。任何帮助都是赞赏和欢迎:)谢谢!

    while(adminLogIn) {
    System.out.println('\u000C');
    System.out.println("Enter Administrator Credentials: ");
    String adminusername = "admin";
    String adminpassword = "admin123";
    TimeUnit.SECONDS.sleep(1);
  JTextField usernameInput = new JTextField(15);
  JTextField passwordInput = new JPasswordField(15);

  JPanel myPanel = new JPanel();
  myPanel.add(new JLabel("Username: "));
  myPanel.add(usernameInput);
  myPanel.add(Box.createHorizontalStrut(15)); // a spacer
  myPanel.add(new JLabel("Password: "));
  myPanel.add(passwordInput);
  String username = usernameInput.getText();
  String password = passwordInput.getText();
  int result = JOptionPane.showConfirmDialog(null, myPanel, 
           "Administrator Login", JOptionPane.OK_CANCEL_OPTION);
    if (username.equals(adminusername) && (password.equals(adminpassword))) {
        System.out.println("Logging In...");
        TimeUnit.SECONDS.sleep(3);
        adminLogIn = false;
    } else {
        System.out.println("Wrong Username/Password. Try Again.");
        attempts++;
    }
    if (attempts == 3) {
        System.out.println("Login Failed. Locking Out User...");
        TimeUnit.SECONDS.sleep(3);
        System.exit(0);
    }
}

1 个答案:

答案 0 :(得分:1)

设置变量用户名和密码时,尚未显示该对话框。所以这些值都是空的。像下面这样更改您的代码:

 while(adminLogIn) {
    System.out.println('\u000C');
    System.out.println("Enter Administrator Credentials: ");
    String adminusername = "admin";
    String adminpassword = "admin123";
    TimeUnit.SECONDS.sleep(1);
  JTextField usernameInput = new JTextField(15);
  JTextField passwordInput = new JPasswordField(15);

  JPanel myPanel = new JPanel();
  myPanel.add(new JLabel("Username: "));
  myPanel.add(usernameInput);
  myPanel.add(Box.createHorizontalStrut(15)); // a spacer
  myPanel.add(new JLabel("Password: "));
  myPanel.add(passwordInput);
  int result = JOptionPane.showConfirmDialog(null, myPanel, 
           "Administrator Login", JOptionPane.OK_CANCEL_OPTION);
    if (usernameInput.getText().equals(adminusername) && (passwordInput.getText().equals(adminpassword))) {
        System.out.println("Logging In...");
        TimeUnit.SECONDS.sleep(3);
        adminLogIn = false;
    } else {
        System.out.println("Wrong Username/Password. Try Again.");
        attempts++;
    }
    if (attempts == 3) {
        System.out.println("Login Failed. Locking Out User...");
        TimeUnit.SECONDS.sleep(3);
        System.exit(0);
    }
}