I have a Java Applet for login form. It has 2 TextFields
, username and password. I need to clear them on clicking Reset
button. This is the code I have written.
public class LoginForm extends Applet implements ActionListener
{
TextField name, pass, hidden;
Button b1, b2;
public void init()
{
name = new TextField(20);
pass = new TextField(20);
b2 = new Button("Reset");
add(name);
add(pass);
add(b2);
b2.addActionListener(this);
}
public void paint(Graphics g)
{
g.drawString("Hello", 10, 150);
}
public void actionPerformed(ActionEvent e) {
System.out.println(e);
name.setText("");
pass.setText("");
repaint();
}
}
But this is not working properly.
Once I click the Reset
button, the actionPerformed()
method gets called and it also calls repaint()
. (I can see "Hello" being displayed).
But the TextFields do not get cleared.
If I make following changes in actionPerformed
name.setText(" "); // please note the spaces
pass.setText(" ");
then it works. But I don't want spaces there. I want the TextFields to get blank.
Any help is appreciated.
Probably it is not good solution, but this is a workaround.Before setting the text invoke getText
method and it will reset. Pretty strange! This behaviour is marked as Bug on this page
public void actionPerformed(ActionEvent e) {
System.out.println(e);
name.getText();
pass.getText();
name.setText("");
pass.setText("");
repaint();
revalidate();
}
Another solution would be setting text with space. But not if you have password-like fields which have setEchoChar('*')
.
public void actionPerformed(ActionEvent e) {
System.out.println(e);
name.setText(" ");
pass.setText(" ");
repaint();
revalidate();
}