Java Swing TableColumn set column header text

Description

Java Swing TableColumn set column header text

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

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.TableColumn;
import javax.swing.table.TableColumnModel;

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[] { Color.red });
      model.addRow(new Object[] { Color.green });
      model.addRow(new Object[] { Color.blue });


      TableColumnModel colModel = table.getColumnModel();
      /*from w w w. jav a2 s  .c om*/
      TableColumn col = colModel.getColumn(0);
      
      col.setHeaderValue("New Name");

      // Force the header to resize and repaint itself
      table.getTableHeader().resizeAndRepaint();
      
      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);
   }

}



PreviousNext

Related