How to search for required elements in list using jface

浪尽此生 提交于 2019-12-12 04:54:04

问题


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.


回答1:


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

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

Looks like this:

Before filtering

After filtering



来源:https://stackoverflow.com/questions/25241236/how-to-search-for-required-elements-in-list-using-jface

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