I want to create Text box with prompt when it is empty. I use setMessage method and it's working fine. How can I change default color of prompt?
Asked
Active
Viewed 1,274 times
1 Answers
1
If you want to change the color of the prompt, just add a Listener
to the focus events.
public class StackOverflow
{
public static void main(String[] args)
{
final Display display = new Display();
Shell shell = new Shell(display);
shell.setText("StackOverflow");
shell.setLayout(new GridLayout(1, true));
final Text text = new Text(shell, SWT.BORDER | SWT.SEARCH);
text.setForeground(display.getSystemColor(SWT.COLOR_RED));
text.setText("Enter something");
text.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, true));
text.addListener(SWT.FocusOut, new Listener()
{
@Override
public void handleEvent(Event arg0)
{
if("".equals(text.getText()))
{
text.setForeground(display.getSystemColor(SWT.COLOR_RED));
text.setText("Enter something");
}
}
});
text.addListener(SWT.FocusIn, new Listener()
{
@Override
public void handleEvent(Event arg0)
{
if("Enter something".equals(text.getText()))
{
text.setForeground(display.getSystemColor(SWT.COLOR_BLACK));
text.setText("");
}
}
});
Label label = new Label(shell, SWT.NONE);
label.setFocus();
label.forceFocus();
shell.pack();
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
Unfocussed/empty:
Focussed/not empty:
As you can see, the "prompt" is now red.

Baz
- 36,440
- 11
- 68
- 94
-
I want to add prompt by: text.setMessage("Enter something"); In your implementation: 1. If I try to read content of empty Text I will get "Enter something" 2. I don't want to clear field on FocusIn. Going with tab key by form will clear all fields. – KrzyH Nov 28 '12 at 15:29
-
@KrzyH I don't understand. The text you set with `setMessage()` will only be visible, when the text field is empty, doesn't it? Then I don't see the problem with clearing it. I changed the `FocusIn` so that it will only clear the field if it contains some text that is different from the prompt. – Baz Nov 28 '12 at 15:55
-
The text you set with setMessage() will only be visible, when the text field is empty.But I want to change default message/prompt text color. – KrzyH Nov 30 '12 at 12:35
-
1@KrzyH Well, you can't change the text color of the prompt. This is why I provided an alternative. – Baz Nov 30 '12 at 12:47