我有一个JTable
,用户应该只能在其中选择一行,但是每当用户选择一行时,其他一些行(根据某种逻辑相关)应该也可以通过编程方式选择。问题是,如果我将表的选择模式设置为 ListSelectionModel.SINGLE_SELECTION
,addRowSelectionInterval
也只会选择一行。有任何想法吗?
编辑:我认为所有想法(自定义选择模型、清除除最后用户选择之外的所有内容、用于突出显示的自定义渲染器)都很好,但最好是使用 SwingX,因为它不需要太多基础结构代码,只需要一个巧妙地使用库。 (当有 SwingX 专家帮忙时,很容易变聪明 :)
最佳答案
有偏见的我会说:在 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);
关于java - JTable:用户单选,编程多选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12004062/