Java Swing TableColumn hide column

Description

Java Swing TableColumn hide column

import java.awt.BorderLayout;
import java.awt.Component;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

public class Main extends JPanel {
   public Main() {
      setLayout(new BorderLayout(5, 5));
      DefaultTableModel model = new DefaultTableModel();

      JTable table = new JTable(model);

      // Add data
      model.addColumn("Col1", new Object[] {"1" });
      model.addColumn("Col2", new Object[] {"2" });
      /* www . j  a v a  2 s  .c om*/
      model.addRow(new Object[] { "a","b"});
      model.addRow(new Object[] { "c","d"});

      JScrollPane sp = new JScrollPane(table);

      hideJTableColumn(table.getColumnModel().getColumn(0)); 
      add(sp, BorderLayout.CENTER);
   }
   /**
    * Hides a specific column of a JTable.
    * <p>
    * @param tc       The table column.
    */
   public static void hideJTableColumn(TableColumn tc) {
       lockJTableColumnWidth(tc, 0);
   }

   /**
    * Locks a Jtable's column width with 'pixels' size.
    * <p>
    * @param tc       The table column.
    * @param pixels    The desired pixels.
    */
   public static void lockJTableColumnWidth(TableColumn tc, int pixels) {
       if (tc != null) {
           tc.setMinWidth(pixels);
           tc.setMaxWidth(pixels);
           tc.setPreferredWidth(pixels);
           tc.setResizable(false);
       }
   }
   public static void main(String[] args) {
      JFrame frame = new JFrame("java2s.com");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      Main m = new Main();
      frame.add(m);
      frame.setSize(300, 210);
      frame.setVisible(true);
   }

}



PreviousNext

Related