JTable hide and show columns

后端 未结 6 889
南旧
南旧 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:32

        HashMap hashMap_columns = new HashMap();
    
        DefaultTableColumnModel defaultTableColumnModel = (DefaultTableColumnModel)jtable.getColumnModel();
    
        Enumeration enumeration = defaultTableColumnModel.getColumns();
    
        while (enumeration.hasMoreElements())
        {
               TableColumn tableColumn = enumeration.nextElement();
    
               hashMap_columns.put((String)tableColumn.getIdentifier(),tableColumn);
    
        }
    
    
        public void setColumnVisible(String identifier, boolean setVisible)
        {
                TableColumn tableColumn = hashMap_columns.get(identifier);
    
                if (setVisible)
                {
                    // using a sorted map removes the need to check column index/position
                    SortedMap sortedMap = new TreeMap();
    
                    // retreive all visible columns 
                    Enumeration enumeration = defaultTableColumnModel.getColumns();
    
                    while (enumeration.hasMoreElements())
                    {
                        TableColumn column = enumeration.nextElement();
    
                        sortedMap.put(column.getModelIndex(),column);
                    }
    
                    // add the column of interest to the sorted map
                    sortedMap.put(tableColumn.getModelIndex(),tableColumn);
    
                    // remove all visible columns
                    for (TableColumn column: sortedMap.values())
                    {
                        defaultTableColumnModel.removeColumn(column);
                    }
    
                    // add all previously visible columns as well as the column of interest
                    for (TableColumn column: sortedMap.values())
                    {
                        defaultTableColumnModel.addColumn(column);
                    }
                }
                else
                {
                    defaultTableColumnModel.removeColumn(tableColumn);
                }
            }
    

提交回复
热议问题