1

我有一个JTable用户应该只能选择一行的地方,但是每当用户选择一行时,也应该以编程方式选择其他一些行(根据某些逻辑相关)。问题是如果我将表格的选择模式设置为ListSelectionModel.SINGLE_SELECTION,addRowSelectionInterval也会只选择一行。有任何想法吗?

编辑:我认为所有想法(自定义选择模型,清除除最后一个用户选择之外的所有选择,自定义渲染器以突出显示)都很好,但最好是使用 SwingX,因为它不需要太多基础设施代码,只需巧妙地使用图书馆。(当 SwingX 专家提供帮助时,很容易变得聪明 :)

4

3 回答 3

3

有偏见的我会说:在 SwingX 中肯定容易得多 :-)

所有你需要的是

  • 决定相关内容的自定义 HighlightPredicate
  • 使用 selectionColors 配置的 ColorHighlighter
  • 在从选择模型接收更改通知时设置自定义谓词

一些代码:

// the custom predicate
public static class RelatedHighlightPredicate implements HighlightPredicate {
    List<Integer> related;

    public RelatedHighlightPredicate(Integer... related) {
        this.related = Arrays.asList(related);

    }
    @Override
    public boolean isHighlighted(Component renderer,
            ComponentAdapter adapter) {
        int modelIndex = adapter.convertRowIndexToModel(adapter.row);
        return related.contains(modelIndex);
    }

}

// its usage
JXTable table = new JXTable(someModel);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final ColorHighlighter hl = new ColorHighlighter(HighlightPredicate.NEVER, 
        table.getSelectionBackground(), table.getSelectionForeground());
table.addHighlighter(hl);
ListSelectionListener l = new ListSelectionListener() {

    @Override
    public void valueChanged(ListSelectionEvent e) {
        if (e.getValueIsAdjusting()) return;
        invokeUpdate((ListSelectionModel) e.getSource());
    }

    private void invokeUpdate(final ListSelectionModel source) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                int singleSelection = source.getMinSelectionIndex();
                if (singleSelection >= 0) {
                    int first = Math.max(0, singleSelection - 2);
                    int last = singleSelection + 2;
                    hl.setHighlightPredicate(new RelatedHighlightPredicate(first, last));
                } else {
                    hl.setHighlightPredicate(HighlightPredicate.NEVER);
                }
            }
        });

    }

};
table.getSelectionModel().addListSelectionListener(l);
于 2012-08-17T12:26:21.617 回答
2

您可以为表格设置多选,但每次选择更改 - 只取 1(最后选择)行,清除其他选择并添加您自己的计算选择。

于 2012-08-17T10:36:09.300 回答
2
  1. The problem is that if I set the selection mode of the table

    用于ListSelectionModel.SINGLE_SELECTION事件来自mousekeyborad

  2. some other rows (that are related according to some logic) should also be selected programmatically

    查看Renderer for JTable,然后需要的行、列或任何可以突出显示的内容,直到程序规则保持不变

  3. ...也许会帮助你

于 2012-08-17T10:52:23.420 回答