Handling editing events in JTextField

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(); } }); } } 
+6
source share
3 answers

For this you need to use DocumentListener on JTextField , here is a tutorial .

As an example:

 userName.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent de){ event(de); } @Override public void removeUpdate(DocumentEvent de) { event(de); } @Override public void changedUpdate(DocumentEvent de){ event(de); } private void event(DocumentEvent de){ error.setVisible(de.getDocument().getLength() == 0); // as mentioned by nIcE cOw better to use Document from parameter frame.revalidate(); frame.repaint(); } }); 

error should be final (for java version lower than 8).

Also at startup, your field is empty, so you may need to use the setVisible(true) label on error .

+4
source

You need to create a 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); 
+5
source

You can add keyListener to the input file

 userName.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent arg0) { } @Override public void keyReleased(KeyEvent arg0) { } @Override public void keyPressed(KeyEvent arg0) { error.setVisible(false); } }); 
0
source

Source: https://habr.com/ru/post/985500/


All Articles