Java - placeholder on textfield

元气小坏坏 提交于 2019-11-27 01:52:05

I found this on the oracle forums.

public class TextFieldWithPrompt extends JTextField{

@Override
protected void paintComponent(java.awt.Graphics g) {
    super.paintComponent(g);

    if(getText().isEmpty() && ! (FocusManager.getCurrentKeyboardFocusManager().getFocusOwner() == this)){
        Graphics2D g2 = (Graphics2D)g.create();
        g2.setBackground(Color.gray);
        g2.setFont(getFont().deriveFont(Font.ITALIC));
        g2.drawString("zip", 5, 10); //figure out x, y from font's FontMetrics and size of component.
        g2.dispose();
    }
  }

https://forums.oracle.com/forums/thread.jspa?threadID=1349874

I use to override the text fields paint method, until I ended up with more custom text fields then I really wanted...

Then I found this prompt API which is simple to use and doesn't require you to extend any components. It also has a nice "buddy" API

This has now been included in the SwingLabs, SwingX library which makes it even eaiser to use...

Panduka Nandara

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!