Posted by Rob Camick on November 29, 2009
Generally text fields are paired with a label when added to a GUI. The label describes the contents of the text field. In some applications you may have noticed that a text prompt appears inside an empty text field. This might be done when space is at a premium or you need to provide addition formatting information for the text.
The TextPrompt class allows you to add this functionality to a text field. The implementation takes advantage of the Swing design that allows you to add child components to any Swing component. So a JLabel containing the prompt text is added to the text field. The main functionality of the TextPrompt class is to determine whether the prompt should be visible or not. The prompt will be removed as soon as text is entered into the Document.
When the Document is empty, the setShow method allows yout to control when the prompt is visible:
- ALWAYS – the prompt is displayed whether the text field has focus or not.
- FOCUS_GAINED – the prompt is displayed when the text field gains focus (and is hidden when focus is lost)
- FOCUS_LOST – the prompt is displayed when the text field loses focus (and is hidden when focus is gained)
There is only one other method that allows you control the behaviour of the prompt:
- setShowPromptOnce – will only display the prompt once. After the text field loses focus for the first time the prompt will no longer be visible.
The Font and foreground Color of the TextPrompt will default from the text field at the time the TextPrompt is created. However, there are a couple of convenience methods that will allow you to customize the appearance of the text in the prompt:
- changeAlpha – allows you to change the alpha value of the foreground Color to provide some transparency
- changeStyle – allows you to change the style of the Font. The values allowed are those supported by the Font class. Common values might be Font.BOLD, Font.ITALIC or Font.BOLD + Font.ITALIC
The code to create the last prompt in the above image was:
JTextField tf7 = new JTextField(10);
TextPrompt tp7 = new TextPrompt("First Name", tf7);
tp7.setForeground( Color.RED );
tp7.changeStyle(Font.BOLD + Font.ITALIC);
tp7.setIcon( ... );
Notice the setIcon() method? As mentioned earlier, the TextPrompt simply extends JLabel to provide its functionality so you can change any property of the label to achieve your desired effect. Be creative, who knows what effect you can achieve!
Although this discussion has dealt with using the TextPrompt on a text field, it can also be used on a JTextArea or JTextPane as well. Using it on a JFormattedTextField that contains formatting characters may prove to be more difficult. I’ll let you experiment with that on your own.