I\'m trying to create a GUI with Swing. My problem is, I have a textfield, but I want it to have a \"placeholder\" (like in html). I read here and there that it can be done
Try this.
private void txtUserNameFocusGained(java.awt.event.FocusEvent evt) {
String username = txtUserName.getText();
if(username.equals("User Name")){
txtUserName.setCaretPosition(0);
}
}
private void txtUserNameFocusLost(java.awt.event.FocusEvent evt) {
String username = txtUserName.getText();
if(username.equals("")){
txtUserName.setForeground(new java.awt.Color(86, 86, 86));
txtUserName.setCaretPosition(0);
txtUserName.setText("User Name");
}
}
private void txtUserNameKeyPressed(java.awt.event.KeyEvent evt) {
String username = txtUserName.getText();
if(username.equals("User Name")){
txtUserName.setForeground(new java.awt.Color(0, 0, 0));
txtUserName.setText(null);
txtUserName.setCaretPosition(0);
}
}
Be adviced, the name of the text field is "txtUserName". You can see the output as like this.