Domanda

I have a Jtable in my gui in which I project some results ! I have also 3 JCheckBoxes that are used as filters ! The problem is that when I check a JCheckBox for first time the results are filtered correctly , but when I uncheck the JCheckBox the results remain the same as with the filter applied , which I don't want to !

JCheckBox Listener :

cEntertainment.addItemListener(new ItemListener(){
        public void itemStateChanged(ItemEvent e){
            int state = e.getStateChange();
            if (state == ItemEvent.SELECTED) {
                man.setEnabled(true);
                woman.setEnabled(true);
                child.setEnabled(true);
                newFilter(cEntertainment.getText());
            } else {
                man.setEnabled(false);
                man.setSelected(false);
                woman.setEnabled(false);
                woman.setSelected(false);
                child.setEnabled(false);
                child.setSelected(false);

            }
        }
    });

newFilter method :

private void newFilter(String type){
    RowFilter<DefaultTableModel,Object> rf = null;
    try{
        rf = RowFilter.regexFilter(type);
    }catch(java.util.regex.PatternSyntaxException e){
        return;
    }
    sorter.setRowFilter(rf);
}
È stato utile?

Soluzione

The problem seems to be you never remove the filter added to the row sorter when the check box is selected. This way the filter will be working regardless the check box status. You should be doing something like this:

cEntertainment.addItemListener(new ItemListener(){
    public void itemStateChanged(ItemEvent e){
        int state = e.getStateChange();
        if (state == ItemEvent.SELECTED) {
            ...
            newFilter(cEntertainment.getText());
        } else {
            ...
            removeFilter();
        }
    }
});

...

private void newFilter(String type) {
    RowFilter<DefaultTableModel,Object> rf = null;
    try{
        rf = RowFilter.regexFilter(type);
    }catch(java.util.regex.PatternSyntaxException e){
        return;
    }
    sorter.setRowFilter(rf);
}

private void removeFilter() {
    sorter.setRowFilter(null);
}

As per DefaultRowSorter.setRowFilter(RowFilter filter) javadoc (remarks are mine):

Sets the filter that determines which rows, if any, should be hidden from the view. The filter is applied before sorting. A value of null indicates all values from the model should be included.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top