Skip to content

Instantly share code, notes, and snippets.

@k33ptoo
Last active April 3, 2019 10:39
Show Gist options
  • Save k33ptoo/97df0019e8e911bbee4392897044a743 to your computer and use it in GitHub Desktop.
Save k33ptoo/97df0019e8e911bbee4392897044a743 to your computer and use it in GitHub Desktop.
A custom hint creator for Java Swing JTextField
//on init components
//add your TextFields Here
JTextField[] tfs = {jTextField1,jTextField2};
setHintText(tfs);
private void setHintText(JTextField[] tfs) {
for (JTextField jtf : tfs) {
jtf.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
//get textfields text and set to empty
if (jtf.getText().equals("JTextField1HintText")) {
jtf.setText("");
} else if (jtf.getText().equals("JTextField2HintText")) {
jtf.setText("");
}
}
@Override
public void focusLost(FocusEvent e) {
//get your textfields if empty and set their initial hint text
if (jtf.equals(jTextField1) && jtf.getText().equals("")) {
jtf.setText("JTextField1HintText");
} else if (jtf.equals(jTextField2) && jtf.getText().equals("")) {
jtf.setText("JTextField2HintText");
}
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment