如何使用jface在列表中搜索所需的元素 [英] How to search for required elements in list using jface

查看:78
本文介绍了如何使用jface在列表中搜索所需的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用swt创建了一个列表,其中显示了动物的列表,例如:猫,狗,骆驼,大象.现在我需要在搜索栏中搜索特定动物的前狗,并且只在列表中显示该动物.因此,如何使用jface做到这一点.我是jface的新手,请帮助我搜索列表.

I have created a list using swt which displays a list of animals ex:cat,dog,camel,elephant. 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 Viewer都支持ViewerFilter. 此处是关于它们的很好的教程.

All JFace Viewers support ViewerFilters. Here is a good tutorial about them.

这是一个非常基本的示例,应向您展示如何使用ViewerFilter s:

Here's a very basic example that should show you how you can use ViewerFilters:

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

看起来像这样:

过滤之前

过滤后

这篇关于如何使用jface在列表中搜索所需的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆