如何更改列表中特定项目的前景色? [英] How to change the foreground color of specific items in a List?

查看:24
本文介绍了如何更改列表中特定项目的前景色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我按下按钮时,我想更改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?

推荐答案

使用 List 执行此操作需要自定义绘图.您最好使用 Table 代替(甚至根据您的要求使用 TableViewer ).这是一个可以满足您要求的表格示例:

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

按钮按下前:

按下按钮后:

请注意:这不是最有效的方法,但应该为您提供基本的想法.

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

这篇关于如何更改列表中特定项目的前景色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆