Java Swing GUI

How to Print a JTable with Image in Header

In this tutorial, we are going to see how to print a JTable with an image in the header. JTable is a flexible Swing component, is a subclass of JComponent class and it can be used to create a table with information displayed in multiple rows and columns. We can create a JTable with a header of type JLabel by customizing the code by implementing the TableCellRenderer interface and we need to redefine the getTableCellRendererComponent() method.


Java Program to Print a JTable with Image in Header:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;

public class Main 
  public static void main(String args[]) 
    //JTable Header
    String columns[] = { "French", "English" };
    //data for JTable in a 2D table
    Object data[][] = { 
        { "Lumière", "Light" },
        { "Cheval", "Horse" }, 
        { "Chien", "Dog" },
        { "Oiseau", "Bird" }, 
        { "Soleil", "Sun" },
        { "Neige", "Snow" }, 
        { "Porte", "Door" },
        { "Voiture", "Car" }, 
        { "Ville", "City" },
        { "Bateau", "Boat" },
        { "Avion", "Plane" } 
    //create a frame
    JFrame f = new JFrame("Print JTable with Image in Header");
    //create a JTable with data
    JTable table = new JTable(data, columns);
    JScrollPane scroll = new JScrollPane(table);

    //create two icons
    ImageIcon icon1 = new ImageIcon("icon1.png");
    ImageIcon icon2 = new ImageIcon("icon2.png");
    //creates a border
    Border headerBorder = UIManager.getBorder("TableHeader.cellBorder");

    //creates two labels with a border
    JLabel label1 = new JLabel(columns[0], icon1, JLabel.CENTER);
    JLabel label2 = new JLabel(columns[1], icon2, JLabel.CENTER);

    //set the renderer
    TableCellRenderer renderer = new JTableCellRenderer();

    //define column model
    TableColumnModel model = table.getColumnModel();

    //get the two columns
    TableColumn col0 = model.getColumn(0);
    TableColumn col1 = model.getColumn(1);



    f.getContentPane().add(scroll, BorderLayout.CENTER);
    f.setSize(300, 300);

//renderer class
class JTableCellRenderer implements TableCellRenderer 
  public Component getTableCellRendererComponent(JTable table, Object 
  value, boolean isSelected, boolean hasFocus, int row, int column) 
    return (JComponent)value;


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

Leave a Reply

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