我有一个登录表单,用户可以输入他的凭据进行登录.我有一个JLabel,用于显示告诉用户用户名不能为空的文本.用户在文本字段为空时单击登录按钮后显示此标签.
我想在用户开始在文本字段中输入的那一刻,带有信息的标签应该消失.我如何实现这种行为?
这是代码:
public class JTextFiledDemo {
private JFrame frame;
JTextFiledDemo() {
frame = new JFrame();
frame.setVisible(true);
frame.setSize(300, 300);
frame.setLayout(new GridLayout(4, 1));
frame.setLocationRelativeTo(null);
iniGui();
}
private void iniGui() {
JLabel error = new JLabel(
" Username cannot be empty!<>");
error.setVisible(false);
JButton login = new JButton("login");
JTextField userName = new JTextField(10);
frame.add(userName);
frame.add(error);
frame.add(login);
frame.pack();
login.addActionListener((ActionEvent) -> {
if (userName.getText().equals("")) {
error.setVisible(true);
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JTextFiledDemo tf = new JTextFiledDemo();
}
});
}
}