Java – handle editing events in jtextfield
•
Java
I have a login form where the user can enter his credentials to log in I have a jlabel to display text that tells the user that the user name cannot be empty This label is displayed when the user clicks the login button when the text field is empty
I think the tag with information should disappear the moment the user starts typing in the text field How do I achieve this behavior?
This 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(); } }); } }
Solution
To do this, you need to use documentlistener on jtextfield, here tutorial
For 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(); } });
The error must be final (for Java versions earlier than 8)
Also, at the beginning, your field is empty, so you may need to use setvisible (true) on the error tag
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码