Highlight particular string in SWT Tree node

隐身守侯 提交于 2019-12-07 18:14:19

问题


I have a requirement like first of all tree will be loaded, tree contains 4 levels.

There is a text field, where user can enter "filterText" and he can press search button.

In tree, in any of four levels if there is a match with filter text, then that particular string only should be highlighted with yellow color but not whole node and its corresponding tree will be expanded.

Unmatched tree nodes should not expand.


回答1:


I assume you are using TreeViewer.

You can use a StyledCellLabelProvider to set different styles for parts of the label string. The DelegatingStyledCellLabelProvider class is derived from this class to make things a bit easier. Set up the label provider using:

viewer.setLabelProvider(new DelegatingStyledCellLabelProvider(myLabelProvider));

where myLabelProvider is a class implementing DelegatingStyledCellLabelProvider.IStyledLabelProvider. The provider has a getImage method as usual plus:

public StyledString getStyledText(Object element)

which uses a StyledString which allows you to apply different styles to the text. Something like:

StyledString text = new StyledString();

text.append("unstyled text");

text.append("styled text with decorations style", StyledString.DECORATIONS_STYLER);

as well as the predefined StyledString.Styler values you can define your own. The DefaultStyler class lets you use colors defined in the JFace color registry.

A simple version of a styler to set the background to yellow would be:

class HighlightStyler extends Styler
{
  @Override
  public void applyStyles(final TextStyle textStyle)
  {
    textStyle.background = Display.getDefault().getSystemColor(SWT.COLOR_YELLOW);
  }
}


来源:https://stackoverflow.com/questions/26173834/highlight-particular-string-in-swt-tree-node

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!