繁体   English   中英

如何更改列表中特定项目的前景色?

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

当我按下按钮时,我想更改List所选项目的前景色。

到目前为止,我已经尝试过了:

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

但它会更改所有项目的前景色,而不仅仅是选定的项目。

任何想法如何解决这个问题?

使用List执行此操作需要自定义工程图。 您最好改用Table (或者根据需要甚至使用TableViewer )。 这是一个表的示例,可以满足您的需求:

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

按下按钮之前:

在此处输入图片说明

按下按钮后:

在此处输入图片说明


请注意:这不是最有效的方法,但是应该给您基本的想法。

列表不支持您想要的。 改用Table和Table项目。 每个表项都代表一行,并且具有setForeground(Color)方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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