JTable动态显示隐藏列

时间:2022-05-29 19:31:24

原文:https://yq.aliyun.com/articles/40833

下面是我总结的一个操作表格列隐藏和显示的工具类:

Java代码  JTable动态显示隐藏列
  1. package com.swing.table;  
  2.   
  3. import javax.swing.JTable;  
  4. import javax.swing.table.TableColumn;  
  5. import javax.swing.table.TableColumnModel;  
  6.   
  7. public class TableUtil3  
  8. {  
  9.       
  10.     private TableUtil3()  
  11.     {  
  12.         throw new Error("Don't let anyone instantiate this class.");  
  13.     }  
  14.       
  15.     /*** 
  16.      * hide specified column 
  17.      *  
  18.      * @param table 
  19.      * @param column 
  20.      */  
  21.     public static void hideTableColumn(JTable table, int column)  
  22.     {  
  23.         TableColumnModel columns = table.getColumnModel();  
  24.         TableColumn column_id_data = columns.getColumn(column);  
  25.         column_id_data.setMaxWidth(0);  
  26.         column_id_data.setPreferredWidth(0);  
  27.         column_id_data.setMinWidth(0);  
  28.           
  29.         TableColumn column_id_header = table.getTableHeader().getColumnModel()  
  30.                 .getColumn(column);  
  31.         column_id_header.setMaxWidth(0);  
  32.         column_id_header.setPreferredWidth(0);  
  33.         column_id_header.setMinWidth(0);  
  34.     }  
  35.     /*** 
  36.      * show specified column 
  37.      *  
  38.      * @param table 
  39.      * @param column 
  40.      * @param width 
  41.      */  
  42.     public static void showTableColumn(JTable table, int column)  
  43.     {  
  44.         int width=40;  
  45.         TableColumnModel columns = table.getColumnModel();  
  46.         TableColumn column_id_data = columns.getColumn(column);  
  47.           
  48.         column_id_data.setMaxWidth(width+100);  
  49.         column_id_data.setPreferredWidth(width);  
  50.         column_id_data.setMinWidth(width);  
  51.          
  52. //        column_id_data.setResizable(true);  
  53.         TableColumn column_id_header = table.getTableHeader().getColumnModel()  
  54.                 .getColumn(column);  
  55.         column_id_header.setMaxWidth(width+100);  
  56.         column_id_header.setPreferredWidth(width);  
  57.         column_id_header.setMinWidth(width);  
  58. //        column_id_header.setResizable(true);  
  59.     }  
  60. }  

调用上述工具类的代码如下: 

//show id column

JButton showIDBtn = new JButton("show id");

showIDBtn.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

TableUtil3.showTableColumn(table, 6);

}

});

button02Pane.add(showIDBtn);

 

//hide id column

JButton hideIDBtn = new JButton("hide id");

hideIDBtn.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

TableUtil3.hideTableColumn(table, 6);

}

});

button02Pane.add(hideIDBtn);