Java Swing TableColumn get column renderer

Description

Java Swing TableColumn get column renderer

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

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

class MyDefaultTableModel extends DefaultTableModel {

   public Class getColumnClass(int mColIndex) {
      int rowIndex = 0;
      Object o = getValueAt(rowIndex, mColIndex);
      if (o == null) {
         return Object.class;
      } else {/*w w  w.jav a 2 s .c o  m*/
         return o.getClass();
      }
   }
}

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

      JTable table = new JTable(model);

      // Add data
      model.addColumn("Col1", new Object[] { Color.red });
      model.addRow(new Object[] { Color.green });
      model.addRow(new Object[] { Color.blue });

      adjustColumnPreferredWidths(table); 

      JScrollPane sp = new JScrollPane(table);

      add(sp, BorderLayout.CENTER);
   }

   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);
   }

   /**
    * Automatically adjust cell width of the given JTable
    * 
    * @param table
    */
   public static void adjustColumnPreferredWidths(JTable table) {
      TableColumnModel columnModel = table.getColumnModel();
      for (int col = 0; col < table.getColumnCount(); col++) {
         int maxwidth = 0;
         TableCellRenderer rend = table.getCellRenderer(Integer.MAX_VALUE, col);
         for (int row = 0; row < table.getRowCount(); row++) {
            Object value = table.getValueAt(row, col);
            Component comp = rend.getTableCellRendererComponent(table, value, false, false, row, col);
            maxwidth = Math.max(comp.getPreferredSize().width, maxwidth);
         }

         TableColumn column = columnModel.getColumn(col);
         TableCellRenderer headerRenderer = column.getHeaderRenderer();
         if (headerRenderer == null)
            headerRenderer = table.getTableHeader().getDefaultRenderer();

         Object headerValue = column.getHeaderValue();
         Component headerComp = headerRenderer.getTableCellRendererComponent(table, headerValue, false, false, 0, col);

         maxwidth = Math.max(maxwidth, headerComp.getPreferredSize().width);

         column.setPreferredWidth(maxwidth);
      }
   }
}



PreviousNext

Related