JTable hide and show columns

后端 未结 6 904
南旧
南旧 2021-01-11 13:03

I want to add some columns to a table (Swing JTable). Some of them will have a default size (e.g. 250), others will be hidden (so their size will be 0). I use this code:

6条回答
  •  误落风尘
    2021-01-11 13:34

    public class TableColumnHider {
    
        private final JTable table;
        private final TableColumnModel tcm;
        private final Map hiddenColumns;
    
        public TableColumnHider(JTable table) {
            this.table = table;
            tcm = table.getColumnModel();
            hiddenColumns = new HashMap();
        }
    
        public void hide(String columnName, String keySig) {
            int index = tcm.getColumnIndex(columnName);
            TableColumn column = tcm.getColumn(index);
            hiddenColumns.put(columnName, column);
            hiddenColumns.put(keySig + columnName, new Integer(index));
            tcm.removeColumn(column);
        }
    
        public void show(String columnName, String keySig) {
            Object o = hiddenColumns.remove(columnName);
            if (o == null) {
                return;
            }
            tcm.addColumn((TableColumn) o);
            o = hiddenColumns.remove(keySig + columnName);
            if (o == null) {
                return;
            }
            int column = ((Integer) o).intValue();
            int lastColumn = tcm.getColumnCount() - 1;
            if (column < lastColumn) {
                tcm.moveColumn(lastColumn, column);
            }
        }
    }
    

提交回复
热议问题