当我在当前的JTable上做出选择时,我编写了下面的代码来创建一个新的JTable:
makeTbale.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
int[] selectedCols = table.getSelectedColumns();
Object[] newCols = new Object[selectedCols.length];
TableModel model = table.getModel();
int selectedRows = model.getRowCount();
Object[][] output = new Object[selectedCols][selectedRows];
for(int nCol = 0; nCol < selectedCols.length; nCol++) {
for{int nRow = 0; nRow<selectedRows;nRow++) {
output[nCol][nRow] = model.getValueAt(nRow, selectedCols[nCol]).toString();
newCols[nCol] = table.getModel().getColumnName(selectedCols[nCol]);
}
}
table.setModel(new DefaultTableModel(output,newCols));
});
现在这是我选择的数据:
Col2 |Col3 |Col5 |Col6 |Col7 |Col10
1/1/2017 |3.45 |1.2 |hello |b1_133 |test
1/2/2017 |3.11 |4.9 |x |b3_122 |you
1/3/2013 |2.98 |5.5 |ask |c1_001 |foo
1/4/2012 |1.90 |2.1 |y |v7_670 |hey
1/6/2000 |9.99 |7.77 |w |c3_890 |fee
1/7/2012 |10.45 |8.75 |test |u0_998 |faa
.
.
.
它可以减少100多行。
这是我运行代码后得到的表格:
Col2 |Col3 |Col5 |Col6 |Col7 |Col10
1/1/2017 |1/2/2017 |1/3/2013 |1/4/2012 |1/6/2000 |1/7/2012
3.45 |3.11 |2.98 |1.90 |9.99 |10.45
1.2 |4.9 |5.5 |2.1 |7.77 |8.75
hello |x |ask |y |w |test
.
.
.
您明白了,所选列现在是行,行是列,只能查看6行(等于列数?)。
我的代码中的错误在哪里?
答案 0 :(得分:1)
表行/列已被交换,因此您混淆了数组索引。
更改
output[nCol][nRow] = model.getValueAt(nRow, selectedCols[nCol]).toString();
到
output[nRow][nCol] = model.getValueAt(nRow, selectedCols[nCol]).toString();
并切换此行的索引:
Object[][] output = new Object[selectedCols][selectedRows];