Java Swing TableColumn get preferred width

Description

Java Swing TableColumn get preferred width

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.SwingConstants;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
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 static void main(String[] args) {
      JFrame frame = new JFrame("java2s.com");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      Main m = new Main();
      frame.add(m);//ww  w  .  j a va  2s.co  m
      frame.setSize(300, 210);
      frame.setVisible(true);
   }
   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" });

      model.addRow(new Object[] { "a", "b" });
      model.addRow(new Object[] { "c", "d" });

      JScrollPane sp = new JScrollPane(table);

      int w = getPreferredColumnHeaderWidth(table, table.getColumnModel().getColumn(0));
      System.out.println(w);
      
      add(sp, BorderLayout.CENTER);
   }

   public static int getPreferredColumnHeaderWidth(JTable table,
         TableColumn col) {
     TableCellRenderer renderer = col.getHeaderRenderer();
     if (renderer == null)
         return 0;
     Component comp = renderer.getTableCellRendererComponent(table,
             col.getHeaderValue(), false, false, 0, 0);
     return comp.getPreferredSize().width;
 }
}



PreviousNext

Related