How to Create Simple HintTextField in Java


What is HintTextField ?
HintTextField display initial text into your TextField.





Now we create an our own HintTextField. Create class HintTextField that extends an JTextField class. Override some properties of JTextField class, to customize and create an our HintTextField. Here we need to override two event focusGained() and focusLost().
We also need other values like Font and Color.
  1. gainFont : Font with  Style Font.PLAIN
  2. lostFont :  Font with Style Font.ITALIC
  3. Color.BLACK
  4. Color.GRAY
When we implements HintTextField we need to keep in mind following some conditions,

  1. Initially, we need to set hint into textfield.
  2. When textfield gain focus we need to First clear hint text from textfield and set an gainFont, Color.BLACK
  3. When textfield lost focus there is again two condition arise
    1. When leaving, textfield does not contain text, that time we again set hint to textfield with lostFont and Color.GRAY
    2. Another is textfield contains some text, then make sure gainFont and Color.BLACK is set to textfield.

HintTextField.java

 import java.awt.Color;  
 import java.awt.Font;  
 import java.awt.event.FocusAdapter;  
 import java.awt.event.FocusEvent;  
 import javax.swing.JTextField;  
   
 public class HintTextField extends JTextField {  
   
   Font gainFont = new Font("Tahoma", Font.PLAIN, 11);  
   Font lostFont = new Font("Tahoma", Font.ITALIC, 11);  
   
   public HintTextField(final String hint) {  
   
     setText(hint);  
     setFont(lostFont);  
     setForeground(Color.GRAY);  
   
     this.addFocusListener(new FocusAdapter() {  
   
       @Override  
       public void focusGained(FocusEvent e) {  
         if (getText().equals(hint)) {  
           setText("");  
           setFont(gainFont);  
         } else {  
           setText(getText());  
           setFont(gainFont);  
         }  
       }  
   
       @Override  
       public void focusLost(FocusEvent e) {  
         if (getText().equals(hint)|| getText().length()==0) {  
           setText(hint);  
           setFont(lostFont);  
           setForeground(Color.GRAY);  
         } else {  
           setText(getText());  
           setFont(gainFont);  
           setForeground(Color.BLACK);  
         }  
       }  
     });  
   
   }  
 }  

How to Use

 JTextField textfield = new HintTextField("Enter your hint");  

or

 HintTextField textfield = new HintTextField("Enter your hint");  


No comments:

Post a Comment