package com.onaro.util.jfc; import java.awt.Color; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import javax.swing.JTextField; import org.apache.commons.lang3.StringUtils; /** * This text field will disply a hint text (grayed out) while is empty and not being edited. * It could be used to help the user understand the information and format to enter the field * Get the text directly from the field and not the document (not supported). */ public class HintedJTextField extends JTextField implements FocusListener{ private static final long serialVersionUID = 1L; private static final Color HINTED_COLOR = Color.gray.brighter(); private String hint; private Color regularColor; public HintedJTextField(String hint) { super(hint); this.hint = hint; this.regularColor = this.getForeground(); setForeground(HINTED_COLOR); addFocusListener(this); } public void focusGained(FocusEvent e) { if (hint.equals(super.getText()) && isFocusOwner()) { super.setText(null); setForeground(regularColor); } } public void focusLost(FocusEvent e) { if (super.getText().length() < 1) { super.setText(hint); setForeground(HINTED_COLOR); } } public String getText() { String text = super.getText(); return text.equals(hint) ? StringUtils.EMPTY : text; } public void setText(String text){ if(text.length() < 1){ text = hint; setForeground(HINTED_COLOR); }else{ setForeground(regularColor); } super.setText(text); } }