下面是我总结的一个操作表格列隐藏和显示的工具类:
- package com.swing.table;
- import javax.swing.JTable;
- import javax.swing.table.TableColumn;
- import javax.swing.table.TableColumnModel;
- public class TableUtil3
- {
- private TableUtil3()
- {
- throw new Error("Don't let anyone instantiate this class.");
- }
- /***
- * hide specified column
- *
- * @param table
- * @param column
- */
- public static void hideTableColumn(JTable table, int column)
- {
- TableColumnModel columns = table.getColumnModel();
- TableColumn column_id_data = columns.getColumn(column);
- column_id_data.setMaxWidth(0);
- column_id_data.setPreferredWidth(0);
- column_id_data.setMinWidth(0);
- TableColumn column_id_header = table.getTableHeader().getColumnModel()
- .getColumn(column);
- column_id_header.setMaxWidth(0);
- column_id_header.setPreferredWidth(0);
- column_id_header.setMinWidth(0);
- }
- /***
- * show specified column
- *
- * @param table
- * @param column
- * @param width
- */
- public static void showTableColumn(JTable table, int column)
- {
- int width=40;
- TableColumnModel columns = table.getColumnModel();
- TableColumn column_id_data = columns.getColumn(column);
- column_id_data.setMaxWidth(width+100);
- column_id_data.setPreferredWidth(width);
- column_id_data.setMinWidth(width);
- // column_id_data.setResizable(true);
- TableColumn column_id_header = table.getTableHeader().getColumnModel()
- .getColumn(column);
- column_id_header.setMaxWidth(width+100);
- column_id_header.setPreferredWidth(width);
- column_id_header.setMinWidth(width);
- // column_id_header.setResizable(true);
- }
- }
调用上述工具类的代码如下:
//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);