Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling editing events in a JTextField

I have a login form where a user can enter his credentials to login. I have a JLabel that serves to display the text telling the user that the user name cannot be empty. This label is display after a user click the login button when the text field is empty.

I want that the moment the user starts typing in the text field the label with the information should disappear.How do I achieve this behavior?

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();
        }
    });
 }
}
like image 944
CN1002 Avatar asked Apr 20 '15 08:04

CN1002


1 Answers

You have to create DocumentListener:

    DocumentListener dl = new DocumentListener()
    {
        @Override
        public void insertUpdate(DocumentEvent de)
        {
            error.setVisible(false);
        }

        @Override
        public void removeUpdate(DocumentEvent de)
        {
            //
        }

        @Override
        public void changedUpdate(DocumentEvent de)
        {
            error.setVisible(false);
        }
    };

then for your text fields:

login.getDocument().addDocumentListener(dl);
like image 62
Kuba Avatar answered Oct 04 '22 19:10

Kuba