Back to Java
2026-04-298 min read

Table Headers (Java)

Learn Table Headers (Java) step by step with clear examples and exercises.

Title: Table Headers (Java) - A full guide to Creating and Customizing Table Headers

Why This Matters

In Java, table headers play a crucial role in organizing data in a tabular format, making it easier for users to understand the meaning of each column. Understanding how to create and customize table headers is essential for creating user-friendly applications that display data effectively. In this lesson, we will learn about various methods to create table headers in Java, explore common mistakes to avoid when working with them, and provide practice questions to test your understanding.

Prerequisites

To follow along with this lesson, you should have a basic understanding of:

  1. Java programming language syntax and structure
  2. JDK (Java Development Kit) installation
  3. Creating Java classes and running programs
  4. Understanding the Swing library for creating graphical user interfaces
  5. Familiarity with control structures, collections, and exception handling in Java
  6. Basic understanding of Object-Oriented Programming concepts

Core Concept

In Java, table headers are created using the JTable class from the Swing library. The JTable class provides a simple way to display tabular data with rows and columns. To create table headers, we will use the TableColumnModel interface, which allows us to customize the properties of each column in a JTable.

Creating a Simple Table with Headers

To create a simple table with headers, follow these steps:

  1. Import necessary libraries:
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
  1. Create a new JFrame and add a JTable to it:
JFrame frame = new JFrame("Simple Table");
JTable table = new JTable();
  1. Add the JTable to the content pane of the JFrame:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(table), BorderLayout.CENTER);
  1. Create a new DefaultTableModel and add data to it:
DefaultTableModel model = new DefaultTableModel();
model.addColumn("Header 1");
model.addColumn("Header 2");
model.addRow(new Object[]{"Data 1", "Data 2"});
model.addRow(new Object[]{"Data 3", "Data 4"});
table.setModel(model);
  1. Set the preferred size of the JFrame and make it visible:
frame.pack();
frame.setVisible(true);

This code creates a simple table with two columns and two rows, with custom headers for each column. The table is displayed inside a scroll pane within a JFrame.

Customizing Table Headers

To customize the appearance of table headers, we can use the TableColumnModel interface. Here's an example of how to change the font and background color of table headers:

  1. Get the TableColumnModel for the JTable:
TableColumnModel columnModel = table.getColumnModel();
  1. Loop through all columns in the TableColumnModel and set their properties:
for (int i = 0; i < columnModel.getColumnCount(); i++) {
TableColumn column = columnModel.getColumn(i);
column.setHeaderValue("Custom Header " + (i + 1));
column.setPreferredWidth(200); // Set preferred width of each column
column.setCellRenderer(new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
setFont(new Font("Arial", Font.BOLD, 16)); // Set font for headers
setBackground(Color.YELLOW); // Set background color for headers
return this;
}
});
}

This code sets custom headers, preferred widths, and styles for each column in the table. The getTableCellRendererComponent method is overridden to set the font and background color of the headers.

Customizing Column Alignment

To customize the alignment of table headers, you can use the setHorizontalAlignment method on the TableColumn object for that column:

column.setHorizontalAlignment(SwingConstants.CENTER); // Center align header text

Customizing Column Resizable

To make a column resizable or non-resizable, use the setResizable method on the TableColumn object for that column:

column.setResizable(false); // Make column non-resizable

Adding Sorting Capabilities to Tables

To add sorting capabilities to a table, you can use the TableRowSorter class from the Swing Extensions library:

  1. Import necessary libraries:
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableRowSorter;
import org.jdesktop.swingx.sort.SortOrder;
  1. Create a new JFrame, JTable, and DefaultTableModel as before.
  2. Add the sorted table to the content pane of the JFrame.
  3. Create a new TableRowSorter object:
TableRowSorter<DefaultTableModel> rowSorter = new TableRowSorter<>(model);
  1. Set the TableRowSorter as the table's row sorter:
table.setRowSorter(rowSorter);
  1. Add sorting capabilities to each column by specifying the desired sort order:
rowSorter.setSortKeys([new SortKey(columnModel.getColumn(0).getModelIndex(), SortOrder.ASCENDING), new SortKey(columnModel.getColumn(1).getModelIndex(), SortOrder.DESCENDING)]);

This code adds sorting capabilities to a table using the TableRowSorter class from the Swing Extensions library.

Worked Example

Let's create a simple application that displays data about employees in a table with customized headers and sorting capabilities. The table will have columns for Name, Age, Gender, and Department, and each header will be centered and bold.

  1. Import necessary libraries:
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableRowSorter;
import org.jdesktop.swingx.sort.SortOrder;
  1. Create a new JFrame, JTable, and DefaultTableModel as before.
  2. Add the sorted table to the content pane of the JFrame.
  3. Create a new TableRowSorter object:
TableRowSorter<DefaultTableModel> rowSorter = new TableRowSorter<>(model);
  1. Set the TableRowSorter as the table's row sorter:
table.setRowSorter(rowSorter);
  1. Customize the headers and set preferred widths for each column:
TableColumnModel columnModel = table.getColumnModel();
for (int i = 0; i < columnModel.getColumnCount(); i++) {
TableColumn column = columnModel.getColumn(i);
column.setHeaderValue("Custom Header " + (i + 1));
column.setPreferredWidth(200); // Set preferred width of each column
}
  1. Add sorting capabilities to each column by specifying the desired sort order:
rowSorter.setSortKeys([new SortKey(columnModel.getColumn(0).getModelIndex(), SortOrder.ASCENDING), new SortKey(columnModel.getColumn(1).getModelIndex(), SortOrder.DESCENDING)]);
  1. Add data to the table:
model.addRow(new Object[]{"John Doe", 30, "Male", "IT"});
model.addRow(new Object[]{"Jane Smith", 28, "Female", "HR"});
model.addRow(new Object[]{"Alice Johnson", 35, "Female", "Finance"});
  1. Set the preferred size of the JFrame and make it visible:
frame.pack();
frame.setVisible(true);

This code creates a simple application that displays employee data in a table with custom headers, sorting capabilities, and centered text for each header.

Common Mistakes

  1. Forgetting to set the preferred width of columns: When creating tables with multiple columns, it's essential to set the preferred width of each column to ensure proper display.
  2. Not setting the TableColumnModel for customization: To customize table headers, you must first get the TableColumnModel for the JTable.
  3. Overlooking the importance of cell renderers: Cell renderers allow you to customize the appearance of individual cells in a table. If you want to change the font or background color of headers, make sure to use a custom cell renderer.
  4. Ignoring the need for horizontal alignment: To center headers, set the SwingConstants.CENTER value for the horizontal alignment property.
  5. Forgetting to repaint the table after customizing headers: After setting custom headers, don't forget to call table.repaint() or frame.repaint() to update the display.
  6. Not handling exceptions when working with user input: When creating tables that allow users to enter data, make sure to handle exceptions such as NumberFormatException and IllegalArgumentException to ensure proper data validation.
  7. Failing to add sorting capabilities to tables: To make it easy for users to sort data in a table, consider adding sorting capabilities using the TableRowSorter class from the Swing Extensions library.
  8. Not testing the application thoroughly: Make sure to test your application with various data sets and edge cases to ensure that it works correctly and handles unexpected input gracefully.

Practice Questions

  1. Create a table that displays data about books with columns for Title, Author, Publisher, and Year Published. Set custom headers for each column and center them. Add sorting capabilities to the table.
  2. Create a table that allows users to enter and edit employee data. Include columns for Name, Age, Gender, Department, Salary, and Position. Customize the headers and make sure the table is editable. Add sorting capabilities to each column based on user input.
  3. Create a table that displays the top 10 countries by population with columns for Country Name, Population, and Capital City. Set custom headers for each column and center them. Add sorting capabilities to the table based on user input.
  4. Create a table that displays data about cars with columns for Make, Model, Year, Mileage, and Color. Customize the headers and make sure the table is sortable by any column. Add the ability to filter the data based on user input for each column.
  5. Create a table that displays data about students in a school with columns for Name, Age, Grade Level, GPA, and Extracurricular Activities. Customize the headers and make sure the table is editable, sortable, and filterable by any column. Add the ability to calculate the total GPA of all students based on user input.

FAQ

  1. How do I create a scrollable table in Java?

To create a scrollable table, add the JTable to a JScrollPane. This will automatically provide horizontal and vertical scrollbars as needed.

  1. Can I customize the background color of individual cells in a table?

Yes, you can customize the background color of individual cells by creating a custom cell renderer and overriding the getTableCellRendererComponent method.

  1. How do I set the preferred width of each column in a table?

To set the preferred width of each column, use the setPreferredWidth method on the TableColumn object for that column.

  1. What is the difference between the JTable and DefaultTableModel classes in Java?

The JTable class provides a graphical representation of tabular data, while the DefaultTableModel class manages the data displayed by the JTable.

  1. How do I sort the data in a table based on a specific column?

To sort the data in a table based on a specific column, use the sortColumn method of the JTable object and pass the index of the column you want to sort by.

  1. How can I make a table editable in Java?

To make a table editable, set the isCellEditable method on the DefaultTableModel for each cell that you want to allow editing.

Table Headers (Java) | Java | XQA Learn