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); label1.setBorder(headerBorder); JLabel label2 = new JLabel(columns[1], icon2, JLabel.CENTER); label2.setBorder(headerBorder); //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); col0.setHeaderRenderer(renderer); col0.setHeaderValue(label1); col1.setHeaderRenderer(renderer); col1.setHeaderValue(label2); f.getContentPane().add(scroll, BorderLayout.CENTER); f.setSize(300, 300); f.setVisible(true); } } //renderer class class JTableCellRenderer implements TableCellRenderer { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { return (JComponent)value; } }
Output: