gpt4 book ai didi

Java JTable 在一行中选择多个连续的单元格

转载 作者:行者123 更新时间:2023-11-30 08:41:12 26 4
gpt4 key购买 nike

我需要能够仅在 JTable 的一行中选择多个连续的单元格。

SINGLE_INTERVAL_SELECTION 最接近我的需要,但我不想选择多行。

单行多列是我想要做的。

有什么办法可以实现吗?

最佳答案

将行的 ListSelectionModel 模式设置为 SINGLE_SELECTION 并将 ColumnModelListSelectionModel 模式设置为 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;
}
}

会导致

Column Interval Selection

关于Java JTable 在一行中选择多个连续的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35217621/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com