我会向您指出自定义 MatcherEditor 截屏视频Matcher
,作为实现您自己的 s 以应对从一组选项中进行过滤的一个很好的参考。
关键部分是创建 a 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);
在上面的示例中,它本身JComboBox
是声明和启动的MatcherEditor
。尽管您需要对正在跟踪的对象的引用,但您无需完全遵循该样式。对我来说,如果我正在观看 Swing 控件,我倾向于声明并启动表单的其余部分,然后传入一个引用,例如
....
private JComboBox nationalityChooser;
public NationalityMatcherEditor(JComboBox alreadyConfiguredComboBox) {
this.nationalityChooser = alreadyConfiguredComboBox;
}
....