Java Swing GUI

How to Change Color of Column in JTable

In this tutorial, we are going to see how to change font color of a column in JTable. JTable is a subclass of JComponent class for displaying complex data structures. JTable component can follow the Model View Controller (MVC) design pattern to display data in rows and columns. A JTable can generate TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener, RowSorterListener interfaces. We can change the background and foreground color for each column of a JTable by customizing the DefaultTableCellRenderer class and it has only one method getTableCellRendererComponent() to implement it.


 

Java Program to Change Color of Column in JTable:
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;

public class JtableColor extends JFrame 
{
   private JTable table;
   private TableColumn col;
   
   public JtableColor() 
   {
      setTitle("Color a JTable column");
    
      //JTable Headers
      String[] columns = new String[] {
          "Id",
          "Name", 
          "Address", 
          "Hourly rate", 
      };

      //data for JTable in a 2D table
      Object[][] data = new Object[][] {
          {1, "Thomas", "Alaska", 20.0 },
          {2, "Jean", "Arizona", 50.0 },
          {3, "Yohan", "California", 30.0, true },
          {4, "Emily", "Florida", 60.0 },
          {5, "Alex", "New York", 10.0 },
      };
 
      //create a JTable with data
      table = new JTable(data, columns);
      //get the 2nd column
      col = table.getColumnModel().getColumn(1);
      //define the renderer
      col.setCellRenderer(new MyRenderer(Color.lightGray, Color.blue));
      //add table to frame
      add(new JScrollPane(table), BorderLayout.CENTER);

      setSize(400, 200);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String [] args) {
      new JtableColor();
   }
}

// Customize the code to set the color for each column in JTable
class MyRenderer extends DefaultTableCellRenderer 
{
   Color bg, fg;
   public MyRenderer(Color bg, Color fg) {
      super();
      this.bg = bg;
      this.fg = fg;
   }
   public Component getTableCellRendererComponent(JTable table, Object 
   value, boolean isSelected, boolean hasFocus, int row, int column) 
   {
      Component cell = super.getTableCellRendererComponent(table, value, 
      isSelected, hasFocus, row, column);
      cell.setBackground(bg);
      cell.setForeground(fg);
      return cell;
   }
}

Output:


mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

One thought on “How to Change Color of Column in JTable

  • Hi, how can i also align the text to the center of the cell component

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *