代码之家  ›  专栏  ›  技术社区  ›  tropikalista

JTable多过滤器设计范式

  •  2
  • tropikalista  · 技术社区  · 17 年前

    正如title所说,我想知道您是否可以指导我阅读一些文档,或者在这里给我一些建议,关于设计(GUI设计)表单,jtable有几个过滤器,它的主要部分由jtable占据,主要目标是避免视觉混乱。

    1 回复  |  直到 17 年前
        1
  •  4
  •   Adamski    17 年前

    我实现了一个简单的 TableFilterPanel 在过去有一个 JTextField 当给定字段中存在文本时,执行正则表达式匹配。我通常把它列为一个垂直标签+文本字段的列表(也就是说,它相当紧凑)。

    我的主课叫 ColumnSearcher ,它提供了制造 RowFilter 使用 文本框 :

    protected class ColumnSearcher {
        private final int[] columns;
        private final JTextField textField;
    
        public ColumnSearcher(int column, JTextField textField) {
            this.columns = new int[1];
            this.textField = textField;
    
            this.columns[0] = column;
        }
    
        public JTextField getTextField() {
            return textField;
        }
    
        public boolean isEmpty() {
            String txt = textField.getText();
            return txt == null || txt.trim().length() == 0;
        }
    
        /**
         * @return Filter based on the associated text field's value, or null if the text does not compile to a valid
         * Pattern, or the text field is empty / contains whitespace.
         */
        public RowFilter<Object, Object> createFilter() {
            RowFilter<Object, Object> ftr = null;
    
            if (!isEmpty()) {
                try {
                    ftr = new RegexFilter(Pattern.compile(textField.getText(), Pattern.CASE_INSENSITIVE), columns);
                } catch(PatternSyntaxException ex) {
                    // Do nothing.
                }
            }
    
            return ftr;
        }
    }
    

    当我想更改过滤器设置时,我从每个单独的过滤器构建一个“和”过滤器:

    protected RowFilter<Object, Object> createRowFilter() {
        RowFilter<Object, Object> ret;
        java.util.List<RowFilter<Object, Object>> filters = new ArrayList<RowFilter<Object, Object>>(columnSearchers.length);
    
        for (ColumnSearcher cs : columnSearchers) {
            RowFilter<Object, Object> filter = cs.createFilter();
            if (filter != null) {
                filters.add(filter);
            }
        }
    
        if (filters.isEmpty()) {
            ret = NULL_FILTER;
        } else {
            ret = RowFilter.andFilter(filters);
        }
    
        return ret;
    }
    

    通常我会发射 PropertyChangeEvent 当我希望更新筛选器并让PropertyChangeListener响应它并重新生成聚合筛选器时。然后您可以选择启动“rowFilter” 属性更改事件 如果用户键入其中一个文本字段(例如,通过添加 DocumentListener 对每个人 文本框 ).

    希望能有所帮助。