我怎样才能做到这一点,当我按下 JButton 时,它会检查您在 JTextFeild 中输入的内容是对还是错? (就像 Java 中的锁一样)

How can I make it so when I press a JButton it checks whether you entered something in JTextFeild is right or wrong? (Just like a lock in Java)

抱歉,如果这个问题已经在某个地方得到了回答,或者我没有理解,但我想知道我是否可以在 JPanel 上创建一个 'lock'。到目前为止,我已经做到了,所以当我按下按钮时,它会清除所有内容并出现一个 JLabel。但是,我做不到,所以当我在 JTextField 中键入内容时,JAVA 会检查我在文本字段中键入的内容是否与 'correct' 用户名匹配。让 JLabel 出现的唯一方法是通过控制台,我不希望这种情况发生。我想要它,所以当我在 JTextField 中键入内容以检查它时。我听说您可以向按钮添加一个 KeyListener 或 addActionListener,但是我该如何实现它们?

同样,我只是 JAVA 的初学者,我不确定我做错了什么,但我只是感到困惑,所以如果你能帮助我,我将不胜感激!

这是我的代码

package Story;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import java.util.Scanner;

@SuppressWarnings("unused")
public class Login {

public static void main(String[] args) {
JFrame frame = new JFrame("Login Page");
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel panel = new JPanel();
frame.add(panel);
placeComponents(panel);

frame.setVisible(true);

}

private static void placeComponents(JPanel panel) {

panel.setLayout(null);

JLabel userLabel = new JLabel("User");
userLabel.setBounds(10, 10, 80, 25);
panel.add(userLabel);

JTextField userText = new JTextField(20);
userText.setBounds(100, 10, 160, 25);
panel.add(userText);

JButton loginButton = new JButton("login");
loginButton.setBounds(10, 80, 80, 25);
panel.add(loginButton);

JButton registerButton = new JButton("register");
registerButton.setBounds(180, 80, 80, 25);
panel.add(registerButton);


   loginButton.addActionListener(new ActionListener() 
   {
        public void actionPerformed(ActionEvent e) {

           loginButton.setVisible(false);

           registerButton.setVisible(false);

           userText.setVisible(false);

           userLabel.setVisible(false);

@SuppressWarnings("resource")
Scanner user = new Scanner (System.in);
String name = user.nextLine();
String accept = "Kenny";
String good; 

if (name.equals(accept)) {
good = "Welcome";

} else {
good = "False. Error";
} 
JLabel label1 = new JLabel(good);
label1.setBounds(100, 40, 100, 100);
       label1.setVisible(true);           
       panel.add(label1);

}


   });
}
}

您在检查时正在从控制台获取输入,那么您期望它如何为您提供正确的结果。

更改以下行:

String name = user.nextLine();

String name = userText.getText();

您应该得到用户输入的文本。