Copy selected data from a jtable in frame1 to another table in frame2

后端 未结 1 1143
挽巷
挽巷 2021-01-17 07:52

I have a JTable2 in frame1 and JTable1 in frame2. I want to copy and send selected data from table2 to table1. how do i do it ?

private void jButton3MouseCl         


        
相关标签:
1条回答
  • 2021-01-17 08:23

    Start by having a look at How to Use Tables.

    If you want to "copy" the selected data, then you will need to know what rows are selected, see JTable#getSelectedRows.

    You're making life difficult for yourself using DbUtils as you've lost the ability to just transfer the objects from one model to another.

    The basic idea would be to copy the values from the original table into a new TableModel and pass that to the second window, something like

    TableModel original = table.getModel();
    DefaultTableModel model = new DefaultTableModel(table.getSelectedRowCount(), original.getColumnCount());
    for (int col = 0; col < original.getColumnCount(); col++) {
        model.addColumn(original.getColumnName(col));
    }
    
    int[] selectedRows = table.getSelectedRows();
    for (int targetRow = 0; targetRow < selectedRows.length; targetRow++) {
        int row = selectedRows[targetRow];
        int modelRow = table.convertRowIndexToModel(row);
        for (int col = 0; col < original.getColumnCount(); col++) {
            model.setValueAt(original.getValueAt(modelRow, col), targetRow, col);
        }
    }
    

    for example. Now you just need to pass model to the second window and apply it to the JTable contained within

    0 讨论(0)
提交回复
热议问题