How do I right-align numbers data in JTable component?

To right-align numbers type of data in JTable cells we need to implements a TableModel. The TableModel‘s interface getColumnClass(int index) implementation return the class of the cell values, this information is used by JTable component to setup a default renderer and editor for the column.

package org.kodejava.swing;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;

public class JTableNumberRightAlign extends JPanel {
    public JTableNumberRightAlign() {

    public static void showFrame() {
        JPanel panel = new JTableNumberRightAlign();

        JFrame frame = new JFrame("JTable Number Align");

    public static void main(String[] args) {

    private void initializeUI() {
        setLayout(new BorderLayout());
        setPreferredSize(new Dimension(500, 500));

        JTable table = new JTable(new NumberTableModel());

        JScrollPane pane = new JScrollPane(table);
        add(pane, BorderLayout.CENTER);

    static class NumberTableModel extends AbstractTableModel {
        String[] columns = {"STUDENT ID", "NAME", "YEARS", "SCORE"};
        Object[][] data = {
                {"S001", "ALICE", 10, 8.75},
                {"S002", "BOB", 10, 7.50},
                {"S003", "CAROL", 10, 9.00},
                {"S004", "MALLORY", 10, 8.50}

        public int getRowCount() {
            return data.length;

        public int getColumnCount() {
            return columns.length;

        public String getColumnName(int column) {
            return columns[column];

        public Object getValueAt(int rowIndex, int columnIndex) {
            return data[rowIndex][columnIndex];

        // This method is used by the JTable to define the default
        // renderer or editor for each cell. For example if you have
        // a boolean data it will be rendered as a checkbox. A
        // number value is right aligned.
        public Class<?> getColumnClass(int columnIndex) {
            return data[0][columnIndex].getClass();

Here is the result of the program:

JTable Number Right Align

JTable Number Right Align


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.