在空文本框中选择提示/消息的颜色

时间:2012-11-27 14:48:09

标签: java eclipse swt

我想创建带有提示的文本框,当它为空时。我使用setMessage method并且它工作正常。如何更改提示的默认颜色?

1 个答案:

答案 0 :(得分:1)

如果您想更改提示的颜色,只需在焦点事件中添加Listener即可。

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();
    }
}

不聚焦/空:

enter image description here

专注/非空:

enter image description here

如您所见,“提示”现在是红色的。