java 如何更改 jface 表的背景选择颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/911834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 14:20:00  来源:igfitidea点击:

How do I change the background selection color for a jface table

javaeclipse-rcpjface

提问by ks.

In a elipse-rcp application I am setting the background color for a row in a jface table but I don't want the selection to change this color. I want to be able to specify the color change for a selected row.

在 elipse-rcp 应用程序中,我正在为 jface 表中的一行设置背景颜色,但我不希望选择更改此颜色。我希望能够为所选行指定颜色更改。

回答by VonC

According to this thread, for JFace Viewers(ListViewer, Table, Tree) by means of using EraseItemand MeasureItemevents

根据这个线程, for JFace Viewers( ListViewer, Table, Tree) 通过使用EraseItemMeasureItem事件

General principle detailed in the article "Custom Drawing Table and Tree Items"

文章“自定义绘图表和树项”中详述的一般原则

SWT.EraseItem: allows a client to custom draw a cell's background and/or selection, and to influence whether the cell's foreground should be drawn

SWT.EraseItem: 允许客户端自定义绘制单元格的背景和/或选择,并影响是否应绘制单元格的前景

alt text

替代文字

回答by ks.

table.addListener(SWT.EraseItem, new Listener() {
    public void handleEvent(Event event) {
        event.detail &= ~SWT.HOT;
        if ((event.detail & SWT.SELECTED) == 0) return; /// item not selected

        Table table =(Table)event.widget;
        TableItem item =(TableItem)event.item;
        int clientWidth = table.getClientArea().width;

        GC gc = event.gc;               
        Color oldForeground = gc.getForeground();
        Color oldBackground = gc.getBackground();

        gc.setBackground(colorBackground);
        gc.setForeground(colorForeground);              
        gc.fillRectangle(0, event.y, clientWidth, event.height);

        gc.setForeground(oldForeground);
        gc.setBackground(oldBackground);
        event.detail &= ~SWT.SELECTED;
    }
});