简体   繁体   中英

How to change the foreground color of specific items in a List?

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?

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:

在此处输入图片说明

After button press:

在此处输入图片说明


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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM