2017-01-16 49 views
1

我遵循這個example to create a simple test with a Table where the foreground color was changed。這按預期工作。如何強制執行TreeItem的前景色,即使它在SWT中被選中

但是,如果我將示例更改爲使用Tree而不是Table,則選擇該項目時不會保留前景色。

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 Tree table = new Tree(shell, SWT.BORDER | SWT.MULTI); 
    table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); 

    for (int i = 0; i < 10; i++) 
    { 
     TreeItem item = new TreeItem(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<TreeItem> allItems = new ArrayList<>(Arrays.asList(table.getItems())); 
      TreeItem[] selItems = table.getSelection(); 

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

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

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

item0被選擇,但顏色爲黑色:

在此代碼段,當按下按鈕,所選項目的前景顏色變爲紅色
enter image description here

但如果我們取消選擇我們可以看到前景顏色實際已更改的項目:
enter image description here

有沒有人知道爲什麼這工作正確Table但不Tree?有沒有辦法做到這一點?

回答

相關問題