I have a login form in which a user can enter their login credentials. I have a JLabel that serves to display text telling the user that the username cannot be empty. This label is displayed after the user presses the login button when the text field is empty.
I want that at the moment when the user begins to enter a text field, the label with the information should disappear. How do I achieve this?
Here is the code:
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( "<html><font color='red'> Username cannot be empty!<></html>"); 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(); } }); } }
source share