Search code examples
swtjfacercpe4tableviewer

How can we filter the table viewer in JFace based on the entered text


I have created a table using table viewer and now i need to filter based on the text entered in the text box so how can we filter the table the code to create table is as follows

TableViewerColumn message = new TableViewerColumn(viewer, SWT.NONE);
        message.getColumn().setWidth(800);
        message.getColumn().setText("Message");
        message.setLabelProvider(new ColumnLabelProvider()
        {
            @Override
            public void update(ViewerCell cell)
            {
                Object element = cell.getElement();
                if(element instanceof MyObject)
                {
                    MyObject obj = (MyObject) element;

                    cell.setText(obj.getMessage());
                }
            }
        });
    }

    private static class MyObject
    {
        private String first;
        private String second;
        private String message;

        public MyObject(String first, String second,String message)
        {
            this.first = first;
            this.second = second;
            this.message = message;
        }

        public String getFirst()
        {
            return first;
        }

        public void setFirst(String first)
        {
            this.first = first;
        }

        public String getSecond()
        {
            return second;
        }

        public void setSecond(String message)
        {
            this.second = second;
        }

        public String getMessage()
        {
            return message;
        }

        public void setMessage(String message)
        {
            this.message = message;
        }

so now how can we filter the table. Please help me as I am new to jface table viewer


Solution

  • Use a class derived from ViewerFilter to add a filter:

    class MyFilter extends ViewerFilter
    {
       @Override
       public boolean select(Viewer viewer, Object parentElement, Object element)
       {
         MyObject obj = (MyObject)element;
    
         // TODO return true to include the object, false to exclude
       }
    }
    

    Add this to the table with:

    viewer.addFilter(new MyFilter());
    

    Call

    viewer.refresh();
    

    to get the viewer to rerun the filter when the text changes.