从其他JTable的选择中制作新的JT



我在下面写了代码,以在当前的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行(等于列数?)。

我的代码中的错误在哪里?

桌子行/cols已交换,因此您已经混合了数组索引。

更改

 output[nCol][nRow] = model.getValueAt(nRow, selectedCols[nCol]).toString();

to

 output[nRow][nCol] = model.getValueAt(nRow, selectedCols[nCol]).toString();

并在此行上切换索引:

Object[][] output = new Object[selectedCols][selectedRows];

最新更新