如何在GlazedList中将JTextField替换为字符串过滤器?

时间:2012-07-01 19:42:35

标签: java swing filter jtable glazedlists

我有一组单选按钮,我想用作我桌子的过滤器。此单选按钮在我的模型类中设置变量。在我的模型中使用getter我检索此值,并且我想在GlazedList表中使用此值作为过滤器。

有人知道怎么做吗?

下面是我的表格,其中JTextField为过滤器:

TextFilterator<Barcode> barcodeFilterator = new TextFilterator<Barcode>() { ... };
    WebTextField searchField = new WebTextField(barcodeModel.getSelectedFilter());
    MatcherEditor<Barcode> textMatcherEditor = new TextComponentMatcherEditor<Barcode>(searchField, barcodeFilterator);
    FilterList<Barcode> filterList = new FilterList<Barcode>(BarcodeUtil.retrieveBarcodeEventList(files), textMatcherEditor);
    TableFormat<Barcode> tableFormat = new TableFormat<Barcode>() { .... };
    EventTableModel<Barcode> tableModel = new EventTableModel<Barcode>(filterList, tableFormat);
    barcodeTable.setModel(tableModel);

1 个答案:

答案 0 :(得分:2)

我会指向Custom MatcherEditor screencast作为实施您自己的Matcher以应对来自一组选项的过滤的良好参考。

关键部分是创建MatcherEditor,在这种情况下,它按国籍过滤人员表。

private static class NationalityMatcherEditor extends AbstractMatcherEditor implements ActionListener {
    private JComboBox nationalityChooser;

    public NationalityMatcherEditor() {
        this.nationalityChooser = new JComboBox(new Object[] {"British", "American"});
        this.nationalityChooser.getModel().setSelectedItem("Filter by Nationality...");
        this.nationalityChooser.addActionListener(this);
    }

    public Component getComponent() {
        return this.nationalityChooser;
    }

    public void actionPerformed(ActionEvent e) {
        final String nationality = (String) this.nationalityChooser.getSelectedItem();
        if (nationality == null)
            this.fireMatchAll();
        else
            this.fireChanged(new NationalityMatcher(nationality));
    }

    private static class NationalityMatcher implements Matcher {
        private final String nationality;

        public NationalityMatcher(String nationality) {
            this.nationality = nationality;
        }

        public boolean matches(Object item) {
            final AmericanIdol idol = (AmericanIdol) item;
            return this.nationality.equals(idol.getNationality());
        }
    }
}

如何使用此MatcherEditor不应该太陌生,因为它与TextMatcherEditor s类似:

EventList idols = new BasicEventList();
NationalityMatcherEditor nationalityMatcherEditor = new NationalityMatcherEditor();
FilterList filteredIdols = new FilterList(idols, nationalityMatcherEditor);

在上面的示例中,JComboBoxMatcherEditor本身中声明并启动。您不需要完全遵循该样式,但需要引用您正在跟踪的对象。对我来说,如果我正在观看Swing控件,我倾向于使用表单的其余部分声明并启动,然后传入引用,例如

....
private JComboBox nationalityChooser;
public NationalityMatcherEditor(JComboBox alreadyConfiguredComboBox) {
    this.nationalityChooser = alreadyConfiguredComboBox;
}
....