Back to Java
2026-04-187 min read

Center Tables (Java)

Learn Center Tables (Java) step by step with clear examples and exercises.

Why This Matters

Centering tables in Java can significantly improve the visual appeal of your applications by providing a balanced layout for data presentation. Centered tables are often used in reports, invoices, and other documents where alignment plays an essential role. They are also useful during interviews or exams as they demonstrate your understanding of Java's formatting capabilities.

Prerequisites

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

  1. Java programming concepts (variables, methods, loops, and conditional statements)
  2. Java Standard Edition (SE) libraries
  3. Basic knowledge of the Java Swing library for creating GUI applications
  4. Familiarity with Object-Oriented Programming (OOP) principles, particularly classes and objects
  5. Understanding of data structures such as arrays and lists
  6. Knowledge of JDBC for connecting to databases if you plan to work on database-related examples

Core Concept

To center a table in Java, we will use the JTable class from the Swing library. The JTable class provides a reusable table component that can be customized according to your needs.

Creating a Simple Table

First, let's create a simple table with two columns and three rows:

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class SimpleTable {
private JFrame frame;
private JTable table;

public static void main(String[] args) {
new SimpleTable();
}

public SimpleTable() {
createAndShowGUI();
}

private void createAndShowGUI() {
frame = new JFrame("Simple Table");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

String[] columnNames = {"Header 1", "Header 2"};
Object[][] data = {
{"Row 1, Col 1", "Row 1, Col 2"},
{"Row 2, Col 1", "Row 2, Col 2"},
{"Row 3, Col 1", "Row 3, Col 2"}
};

DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model);

frame.add(new JScrollPane(table), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}

In this example, we create a simple JFrame, set its title, and add a JTable to the center of the frame using a JScrollPane. The table data is stored in a two-dimensional array, and the column names are stored in an array. We then create a DefaultTableModel with our data and column names, and use it to populate our table.

Centering the Table

To center the table within the frame, we need to set the layout manager of the frame to a suitable layout that allows us to center components. One such layout is the BorderLayout. We can modify our createAndShowGUI method as follows:

private void createAndShowGUI() {
frame = new JFrame("Centered Table");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());

String[] columnNames = {"Header 1", "Header 2"};
Object[][] data = {
{"Row 1, Col 1", "Row 1, Col 2"},
{"Row 2, Col 1", "Row 2, Col 2"},
{"Row 3, Col 1", "Row 3, Col 2"}
};

DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model);

frame.add(new JScrollPane(table), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}

Now our table is centered within the frame.

Creating a More Complex Table

Let's create a more complex example with a centered table that displays data from an array of objects:

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.DefaultTableModel;

public class CenteredTableExample {
private JFrame frame;
private JTable table;

public static void main(String[] args) {
new CenteredTableExample();
}

public CenteredTableExample() {
createAndShowGUI();
}

private void createAndShowGUI() {
frame = new JFrame("Centered Table Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());

List<Person> people = getPeople();

String[] columnNames = {"Name", "Age"};
Object[][] data = new Object[people.size()][2];

for (int i = 0; i < people.size(); i++) {
Person person = people.get(i);
data[i] = new Object[]{person.getName(), person.getAge()};
}

DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model);
table.setFont(new Font("Serif", Font.PLAIN, 16));

frame.add(new JScrollPane(table), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}

private List<Person> getPeople() {
List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 25));
people.add(new Person("Bob", 30));
people.add(new Person("Charlie", 35));
return people;
}
}

class Person {
private String name;
private int age;

public Person(String name, int age) {
this.name = name;
this.age = age;
}

public String getName() {
return name;
}

public int getAge() {
return age;
}
}

In this example, we create a list of Person objects and populate our table with their names and ages. We also set the font of the table to make it more readable.

Worked Example

Let's expand on the previous worked example by adding sorting functionality:

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

public class SortedCenteredTableExample {
private JFrame frame;
private JTable table;

public static void main(String[] args) {
new SortedCenteredTableExample();
}

public SortedCenteredTableExample() {
createAndShowGUI();
}

private void createAndShowGUI() {
frame = new JFrame("Sorted Centered Table Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());

List<Person> people = getPeople();

String[] columnNames = {"Name", "Age"};
Object[][] data = new Object[people.size()][2];

for (int i = 0; i < people.size(); i++) {
Person person = people.get(i);
data[i] = new Object[]{person.getName(), person.getAge()};
}

DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model);
table.setFont(new Font("Serif", Font.PLAIN, 16));

TableRowSorter<DefaultTableModel> sorter = new TableRowSorter<>(model);
table.setRowSorter(sorter);

frame.add(new JScrollPane(table), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}

private List<Person> getPeople() {
List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 25));
people.add(new Person("Bob", 30));
people.add(new Person("Charlie", 35));
return people;
}

class Person {
private String name;
private int age;

public Person(String name, int age) {
this.name = name;
this.age = age;
}

public String getName() {
return name;
}

public int getAge() {
return age;
}
}
}

In this expanded example, we add a TableRowSorter to sort the table data in ascending order by age. We also create a JFrame with a title and set its layout to BorderLayout. The rest of the code remains the same as the previous worked example.

Common Mistakes

  1. Forgetting to set the layout manager: Make sure you set the layout manager of your frame (or container) to a suitable layout that allows centering components, such as BorderLayout.
  2. Not specifying the correct component position in the layout: When using a BorderLayout, ensure that you add the table to the CENTER position instead of other positions like NORTH, SOUTH, EAST, or WEST.
  3. Forgetting to pack and setVisible: After setting up your GUI components, don't forget to call pack() on the frame and setVisible(true) to make it appear on the screen.
  4. Not handling resizing properly: If you want your table to automatically adjust its size when the window is resized, consider using a layout that supports proportional sizing, such as GridBagLayout.
  5. Forgetting to sort the data: When working with sorted tables, make sure you initialize the sorter and call sort() on it after populating the table.
  6. Not handling exceptions properly: Always wrap your code in a try-catch block to handle potential exceptions, such as NullPointerException.
  7. Ignoring readability: Use meaningful variable names, proper indentation, and comments to make your code more readable and easier to maintain.

Practice Questions

  1. Create a centered table that displays data from an array of strings.
  2. Modify the example provided in the Worked Example section to sort the people by age in ascending order.
  3. Create a centered table that displays data from a database using JDBC.
  4. Implement a resizable centered table using GridBagLayout.
  5. Add filtering functionality to the sorted table example, allowing users to search for specific names or ages.
  6. Create a GUI with multiple centered tables displaying different datasets.
  7. Implement a function that centers a given component within its container using any layout manager of your choice.
  8. Create a custom JTable class that extends the default functionality, adding new features such as sorting by multiple columns or row hover effects.

FAQ

  1. Why can't I center my table using FlowLayout?
  • A FlowLayout does not provide a straightforward way to center components. Instead, use a layout that supports centering, such as BorderLayout.
  1. How do I make my table scrollable when it exceeds the frame size?
  • Wrap your table in a JScrollPane to enable scrolling when the table exceeds the frame's size.
  1. Can I center my table using absolute positioning?
  • While you can use absolute positioning (setLocation()) to center your table, it is not recommended because it makes your GUI less flexible and harder to resize or adapt to different screen sizes. Instead, use a layout that supports centering components.
  1. How do I sort my table data in descending order instead of ascending order?
  • To sort your table data in descending order, simply reverse the order of the elements in the comparator passed to the TableRowSorter. For example:
Collections.reverseOrder()
  1. How can I make my table columns resizable by the user?
  • To allow users to resize your table columns, set the autoResizeMode property of the table to JTable.AUTO_RESIZE_ALL_COLUMNS. For example:
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
  1. How can I add a drop-down menu to each cell in my table
Center Tables (Java) | Java | XQA Learn