简体   繁体   English

如何使用jface在列表中搜索所需元素

[英]How to search for required elements in list using jface

I have created a list using swt which displays a list of animals ex:cat,dog,camel,elephant. 我使用swt创建了一个列表,其中显示了动物的列表,例如:猫,狗,骆驼,大象。 and now i need to search for a specific animal ex dog in search coloumn and only that animal has to be displayed in the list .So how can this be done using jface.I am new to jface,Please help me to search the list. 现在我需要在搜索栏中搜索特定动物的前狗,并且只在列表中显示该动物。因此,如何使用jface做到这一点。我是jface的新手,请帮助我搜索列表。

All JFace Viewer s support ViewerFilter s. 所有JFace Viewer支持ViewerFilter Here is a good tutorial about them. 是关于它们的很好的教程。

Here's a very basic example that should show you how you can use ViewerFilter s: 这是一个非常基本的示例,应向您展示如何使用ViewerFilter

public static void main(String[] args)
{
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("StackOverflow");
    shell.setLayout(new GridLayout(1, false));

    List<String> input = new ArrayList<>();
    input.add("Dodo");
    input.add("Unicorn");

    final MyFilter filter = new MyFilter();

    final ListViewer viewer = new ListViewer(shell);
    viewer.getList().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    viewer.setContentProvider(new ArrayContentProvider());
    viewer.setInput(input);
    viewer.addFilter(filter);

    Text text = new Text(shell, SWT.BORDER);
    text.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
    text.addListener(SWT.Verify, new Listener()
    {
        @Override
        public void handleEvent(Event e)
        {
            final String oldS = ((Text) e.widget).getText();
            final String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);

            filter.setSearchText(newS);
            viewer.refresh();
        }
    });

    shell.pack();
    shell.open();

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

private static class MyFilter extends ViewerFilter
{
    private String searchString;

    public void setSearchText(String s)
    {
        this.searchString = ".*" + s + ".*";
    }

    @Override
    public boolean select(Viewer viewer, Object parentElement, Object element)
    {
        if (searchString == null || searchString.length() == 0)
        {
            return true;
        }

        String p = (String) element;

        if (p.matches(searchString))
        {
            return true;
        }

        return false;
    }
}

Looks like this: 看起来像这样:

Before filtering 过滤之前

在此处输入图片说明

After filtering 过滤后

在此处输入图片说明

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

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