Java Swing TableColumn set column width by column text

Description

Java Swing TableColumn set column width by column text

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" });
      /*from w  ww . j a  v a 2s  .  c om*/
      model.addRow(new Object[] { "a","b"});
      model.addRow(new Object[] { "c","d"});

      fixSize(table.getColumn(0),table); 

      // Force the header to resize and repaint itself
      table.getTableHeader().resizeAndRepaint();
      
      JScrollPane sp = new JScrollPane(table);

      add(sp, BorderLayout.CENTER);
   }
   /**
    * Fix the size of a column according to the header text.
    *
    * @param column to be resized
    * @param table containing the column
    */
   public static void fixSize(TableColumn column, JTable table) {
       TableCellRenderer rndr;
       rndr = column.getHeaderRenderer();
       if (rndr == null) {
           rndr = table.getTableHeader().getDefaultRenderer();
       }
       Component c = rndr.getTableCellRendererComponent(table,
               column.getHeaderValue(), false, false, -1,
               column.getModelIndex());
       int width = c.getPreferredSize().width + 10;
       column.setMaxWidth(width);
       column.setPreferredWidth(width);
       column.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