java 从 JTable 中的选定列获取数据的简单方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16338039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Easy way to get the data from selected columns in JTable
提问by ArmMiner
I have a JTable
and want to get the data from each selected column. The columns are selected by mouse clicks. So, if there are 5 columns selected, the output has to be 5 string arrays.
我有一个JTable
并想从每个选定的列中获取数据。通过鼠标点击选择列。因此,如果选择了 5 列,则输出必须是 5 个字符串数组。
I'm trying to do this by MouseListener
, but I can get only the clicked cells, not the entire column.
我正在尝试通过 执行此操作MouseListener
,但我只能获取单击的单元格,而不是整个列。
回答by johnchen902
You need JTable.getSelectedColumns()
, but it returns the selected column indexes, so you need to access the TableModel
(package javax.swing.table
)
您需要JTable.getSelectedColumns()
,但它返回选定的列索引,因此您需要访问TableModel
(包javax.swing.table
)
int[] columns = jtable.getSelectedColumns();
TableModel model = jtable.getModel();
int rowcount = model.getRowCount();
String[][] output = new String[columns.length][rowcount];
for (int i = 0; i < columns.length; i++)
for (int row = 0; row < rowcount; row++){
int column = jtable.convertColumnIndexToModel(columns[i]);
output[i][row] = model.getValueAt(row, column).toString();
}