How to make a columns in JTable Invisible for Swing Java

前端 未结 8 1448
半阙折子戏
半阙折子戏 2020-12-03 04:44

I have designed one GUI in which I have used one JTable from which I have to make 2 columns invisible . How should I do that ?

8条回答
  •  一整个雨季
    2020-12-03 04:48

    I tried 2 possible solutions that both work, but got some issue with the 1st solution.

       table.removeColumn(table.getColumnModel().getColumn(4));
    

    or

       table.getColumnModel().getColumn(4).setMinWidth(0);
       table.getColumnModel().getColumn(4).setMaxWidth(0);
       table.getColumnModel().getColumn(4).setWidth(0);
    

    In my recent case, I preferred the 2nd solution because I added a TableRowSorter.

       TableRowSorter sorter = new TableRowSorter(model);
       table.setRowSorter(sorter);
    

    When using table.removeColumn(table.getColumnModel().getColumn(4)), it will physically remove the column from the view/table so you cannot use table.getValueAt(row, 4) - it returns ArrayIndexOutOfBounds. The only way to get the value of the removed column is by calling table.getModel().getValueAt(table.getSelectedRow(),4). Since TableRowSorter sorts only what's on the table but not the data in the DefaultTableModel object, the problem is when you get the value after sorting the records - it will retrieve the data from DefaultModelObject, which is not sorted.

    So I used the 2nd solution then used table.getValueAt(table.getSelectedRow(),4);

    The only issue I see with the 2nd approach was mentioned by @camickr: "When you set the width to 0, try tabbing, when you hit the hidden column focus disappears until you tab again. This will confuse users."

提交回复
热议问题