0

When I press a button, I want to change the foreground color of the selected item in a List.

So far, I tried this:

list.setForeground(display.getSystemColor(SWT.COLOR_RED));

but it changes the foreground color of all the items, not just the selected one.

Any ideas how to solve this?

4

2 回答 2

2

Doing this with a List would require custom drawing. You are better off using a Table instead (or even a TableViewer depending on your requirements). Here is an example of a table that does what you want:

public static void main(String[] args)
{
    final Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new GridLayout(1, false));
    shell.setText("StackOverflow");

    final Table table = new Table(shell, SWT.BORDER | SWT.MULTI);
    table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

    for (int i = 0; i < 10; i++)
    {
        TableItem item = new TableItem(table, SWT.NONE);
        item.setText("item " + i);
    }

    Button button = new Button(shell, SWT.PUSH);
    button.setText("Color selected");

    button.addListener(SWT.Selection, new Listener()
    {
        @Override
        public void handleEvent(Event arg0)
        {
            List<TableItem> allItems = new ArrayList<>(Arrays.asList(table.getItems()));
            TableItem[] selItems = table.getSelection();

            for (TableItem item : selItems)
            {
                item.setForeground(display.getSystemColor(SWT.COLOR_RED));
                allItems.remove(item);
            }

            for (TableItem item : allItems)
            {
                item.setForeground(display.getSystemColor(SWT.COLOR_LIST_FOREGROUND));
            }
        }
    });

    shell.pack();
    shell.open();
    while (!shell.isDisposed())
    {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

Before button press:

enter image description here

After button press:

enter image description here


Just a note: This is not the most efficient way to do it, but should give you the basic idea.

于 2013-04-25T09:18:56.587 回答
1

List does not supports what you want. Use Table and Table items instead. Each table item represent a row, and it has setForeground(Color) method.

于 2013-04-25T09:21:06.897 回答