【发布时间】:2016-05-15 01:04:35
【问题描述】:
我需要能够仅在JTable 中选择单行中的多个连续单元格。
SINGLE_INTERVAL_SELECTION 最接近我的需要,但我不想选择多行。
单行多列是我想要做的。
有没有办法做到这一点?
【问题讨论】:
标签: java swing jtable multipleselection
我需要能够仅在JTable 中选择单行中的多个连续单元格。
SINGLE_INTERVAL_SELECTION 最接近我的需要,但我不想选择多行。
单行多列是我想要做的。
有没有办法做到这一点?
【问题讨论】:
标签: java swing jtable multipleselection
将行的ListSelectionModel 模式设置为SINGLE_SELECTION,将ColumnModel 的ListSelectionModel 模式设置为SINGLE_INTERVAL_SELECTION,并告诉ColumnModel 允许选择列。
public class Main {
public static void main(String[] args) {
JTable jTable = new JTable();
TableColumnModel columnModel = jTable.getColumnModel();
columnModel.setColumnSelectionAllowed(true);
ListSelectionModel columnSelectionModel = columnModel.getSelectionModel();
columnSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
ListSelectionModel rowSelectionModel = jTable.getSelectionModel();
rowSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jTable.setModel(createExampleModel());
createFrameAndShow(jTable);
}
private static void createFrameAndShow(JTable jTable) {
JFrame mainFrame = new JFrame("JTable select multiple contiguous cells in a single row");
Container contentPane = mainFrame.getContentPane();
contentPane.add(jTable);
mainFrame.setSize(500, 100);
mainFrame.setLocationRelativeTo(null);
mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
}
private static DefaultTableModel createExampleModel() {
DefaultTableModel defaultTableModel = new DefaultTableModel();
defaultTableModel.setColumnCount(4);
defaultTableModel.addRow(new Object[] { "A1", "B1", "C1", "D1" });
defaultTableModel.addRow(new Object[] { "A2", "B2", "C2", "D2" });
defaultTableModel.addRow(new Object[] { "A3", "B3", "C3", "D3" });
return defaultTableModel;
}
}
会导致
【讨论】:
你需要这个:
table.setRowSelectionAllowed ( false );
table.setCellSelectionEnabled ( true );
另一种方式是:
table.setColumnSelectionAllowed(true);
table.setRowSelectionAllowed(true);
无论使用哪种方式,您都可以使用Ctrl 键连续选择多个单元格。
祝你好运。
【讨论】:
【讨论】: