How do I create a scrollable JTable component?

To create a scrollable JTable component we have to use a JScrollPane as the container of the JTable. Beside that we also need to set the table auto resize mode to JTable.AUTO_RESIZE_OFF so that a horizontal scroll bar displayed by the scroll pane when needed. If we do not turn off the auto resize mode the colums of the table will be resized to fit the available window size.

package org.kodejava.example.swing;

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

public class ScrollableJTable extends JPanel {
    public ScrollableJTable() {

    private void initializeUI() {
        setLayout(new BorderLayout());
        setPreferredSize(new Dimension(400, 200));
        JTable table = new JTable(20, 20);
        // Turn off JTable's auto resize so that JScrollpane
        // will show a horizontal scroll bar.
        JScrollPane pane = new JScrollPane(table);
        add(pane, BorderLayout.CENTER);

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

        JFrame frame = new JFrame();
        frame.setTitle("Scrollable JTable");

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply