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 columns 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() {
        initializeUI();
    }

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

        JTable table = new JTable(20, 20);

        // Turn off JTable's auto resize so that JScrollPane will show a
        // horizontal scroll bar.
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

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

    private static void showFrame() {
        JPanel panel = new ScrollableJTable();
        panel.setOpaque(true);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setTitle("Scrollable JTable");
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

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

Below is the result of the code snippet above.

Scrollable JTable Component Demo

How do I programmatically select JTable’s columns?

This program shows you how to select some columns in the JTable programmatically. Below we demonstrates how to select columns using the setColumnSelectionInterval() method, remove or clear column selection using removeColumnSelectionInterval() method and use the addColumnSelectionInterval() to add more columns to the previously selected columns.

package org.kodejava.example.swing;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class JTableColumnSelectProgrammatically extends JPanel {
    public JTableColumnSelectProgrammatically() {
        initializePanel();
    }

    private void initializePanel() {
        setLayout(new BorderLayout());
        setPreferredSize(new Dimension(475, 200));

        final JTable table = new JTable(new MyTableModel());
        table.setFillsViewportHeight(true);
        JScrollPane pane = new JScrollPane(table);

        JLabel label1 = new JLabel("From col: ");
        final JTextField field1 = new JTextField(3);
        JLabel label2 = new JLabel("To col: ");
        final JTextField field2 = new JTextField(3);
        JButton select = new JButton("Select");
        JButton clear = new JButton("Clear");
        JButton add = new JButton("Add another one");

        // Enables column selection mode and disable row
        // selection mode.
        table.setColumnSelectionAllowed(true);
        table.setRowSelectionAllowed(false);

        // Select columns based on the input.
        select.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                int index1 = 0;
                int index2 = 0;
                try {
                    index1 = Integer.valueOf(field1.getText());
                    index2 = Integer.valueOf(field2.getText());
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }

                if (index1 < 0 || index2 < 0 ||
                    index1 >= table.getColumnCount() ||
                    index2 >= table.getColumnCount()) {
                    JOptionPane.showMessageDialog(table, "Selection out of range!");
                } else {
                    table.setColumnSelectionInterval(index1, index2);
                }
            }
        });

        // Clears column selection
        clear.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                table.removeColumnSelectionInterval(0, table.getColumnCount() - 1);
                field1.setText("");
                field2.setText("");
            }
        });

        // Add one more column after the last selected column.
        add.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                int index2 = 0;
                try {
                    index2 = Integer.valueOf(field2.getText());
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }

                index2 = index2 + 1;
                table.addColumnSelectionInterval(index2, index2);
                field2.setText(String.valueOf(index2));
            }
        });

        JPanel command = new JPanel(new FlowLayout());
        command.add(label1);
        command.add(field1);
        command.add(label2);
        command.add(field2);
        command.add(select);
        command.add(clear);
        command.add(add);

        add(pane, BorderLayout.CENTER);
        add(command, BorderLayout.SOUTH);
    }

    public static void showFrame() {
        JPanel panel = new JTableColumnSelectProgrammatically();
        panel.setOpaque(true);

        JFrame frame = new JFrame("JTable Column Selection");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

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

    public class MyTableModel extends AbstractTableModel {
        private String[] columns = {"ID", "NAME", "AGE", "A STUDENT?"};
        private Object[][] data = {
            {1, "Alice", 20, Boolean.FALSE},
            {2, "Bob", 10, Boolean.TRUE},
            {3, "Carol", 15, Boolean.TRUE},
            {4, "Ignasia", 17, Boolean.TRUE},
            {5, "Mallory", 25, Boolean.FALSE}
        };

        public int getRowCount() {
            return data.length;
        }

        public int getColumnCount() {
            return columns.length;
        }

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

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

        // 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 check box. A
        // number value is right aligned.
        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return data[0][columnIndex].getClass();
        }
    }

}

Below is the screen capture of the program.

Programmatically Select JTable Column

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.example.swing;

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

public class JTableNumberRightAlign extends JPanel {
    public JTableNumberRightAlign() {
        initializeUI();
    }

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

        JTable table = new JTable(new NumberTableModel());
        table.setFillsViewportHeight(true);

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

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

        JFrame frame = new JFrame("JTable Number Align");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

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

    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", "IGNASIA", 10, 9.00},
            {"S005", "MALLORY", 10, 8.50}
        };

        public int getRowCount() {
            return data.length;
        }

        public int getColumnCount() {
            return columns.length;
        }

        @Override
        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 check box. A
        // number value is right aligned.
        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return data[0][columnIndex].getClass();
        }
    }
}

Here is the result of the program:

JTable Number Right Align

How do I render boolean value as checkbox in JTable component?

To make a JTable renders a boolean as a checkbox in the table cell we need to tell the table that a cell stores a boolean type of data. To do this we have to implement a TableModel for the JTable component.

TableModel‘s getColumnClass(int columnIndex) must return the type of data stored in a cell. When it returns that the column stored a Boolean data, JTable displays a checkbox as the default renderer or editor for that cell.

package org.kodejava.example.swing;

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

public class JTableBooleanAsCheckbox extends JPanel {
    public JTableBooleanAsCheckbox() {
        initializeUI();
    }

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

        JTable table = new JTable(new BooleanTableModel());
        table.setFillsViewportHeight(true);
        JScrollPane pane = new JScrollPane(table);
        add(pane, BorderLayout.CENTER);
    }

    public static void showFrame() {
        JPanel panel = new JTableBooleanAsCheckbox();
        panel.setOpaque(true);

        JFrame frame = new JFrame("JTable Boolean as Checkbox");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

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

    class BooleanTableModel extends AbstractTableModel {
        String[] columns = {"STUDENT ID", "NAME", "SCORE", "PASSED"};
        Object[][] data = {
            {"S001", "ALICE", 90.00, Boolean.TRUE},
            {"S002", "BOB", 45.50, Boolean.FALSE},
            {"S003", "CAROL", 60.00, Boolean.FALSE},
            {"S004", "IGNASIA", 85.80, Boolean.TRUE},
            {"S005", "MALLORY", 75.80, Boolean.TRUE}
        };

        public int getRowCount() {
            return data.length;
        }

        public int getColumnCount() {
            return columns.length;
        }

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

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

        // 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 check box. A
        // number value is right aligned.
        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return data[0][columnIndex].getClass();
        }
    }
}

Here is the result of the program:

JTable render Boolean as Checkbox

How do I disable or enable JTable cell selection?

Disables or enables JTable‘s cell selection can be done by calling the setCellSelectionEnabled(boolean cellSelectionEnabled) method. This method accept a boolean value. Calling this method also changes the state of table’s row and column selection respectively.

To completely remove the selection capability from JTable component we can change its focusable state to false by calling the setFocusable(boolean focusable) method.

package org.kodejava.example.swing;

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

public class JTableDisableSelection extends JPanel {
    public JTableDisableSelection() {
        initializePanel();
    }

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

        JTable table = new JTable(new PremiereLeagueTableModel());
        table.getColumnModel().getColumn(0).setMinWidth(150);

        // Disable table's cell selection.
        table.setCellSelectionEnabled(false);

        // Settings table focus to false completely remove selection
        // capability from the table component.
        table.setFocusable(false);

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

    public static void showFrame() {
        JPanel panel = new JTableDisableSelection();
        panel.setOpaque(true);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("JTable Disable Selection");
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

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

    class PremiereLeagueTableModel extends AbstractTableModel {
        // TableModel's column names
        private String[] columnNames = {
            "TEAM", "P", "W", "D", "L", "GS", "GA", "GD", "PTS"
        };

        // TableModel's data
        private Object[][] data = {
            {"Liverpool", 3, 3, 0, 0, 7, 0, 7, 9},
            {"Tottenham", 3, 3, 0, 0, 8, 2, 6, 9},
            {"Chelsea", 3, 3, 0, 0, 8, 3, 5, 9},
            {"Watford", 3, 3, 0, 0, 7, 2, 5, 9},
            {"Manchester City", 3, 2, 1, 0, 9, 2, 7, 7}
        };

        public int getRowCount() {
            return data.length;
        }

        public int getColumnCount() {
            return columnNames.length;
        }

        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }

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

Disable or Enable JTable Cell Selection

How do I get the selected cells in JTable component?

The following examples shows you how to get the selected rows or the selected columns or the selection of multiple cells in the JTable component. To listen for selection event we can add a selection listener to JTable component by calling the JTable.getSelectionModel().addListSelectionListener() method. This method accepts an object which implements a ListSelectionListener interface.`

package org.kodejava.example.swing;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;

public class JTableGetSelectedCells extends JPanel {
    private JTable table = null;

    public JTableGetSelectedCells() {
        initializePanel();
    }

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

        table = new JTable(new PremiereLeagueTableModel());
        table.getColumnModel().getColumn(0).setMinWidth(150);
        table.getSelectionModel().addListSelectionListener(
            new RowColumnListSelectionListener());

        table.setFillsViewportHeight(true);
        JScrollPane pane = new JScrollPane(table);

        JPanel control = new JPanel(new FlowLayout());
        final JCheckBox cb1 = new JCheckBox("Row Selection");
        final JCheckBox cb2 = new JCheckBox("Columns Selection");
        final JCheckBox cb3 = new JCheckBox("Cells Selection");

        // Change row selection allowed state
        cb1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                table.setRowSelectionAllowed(cb1.isSelected());
                table.setColumnSelectionAllowed(!cb1.isSelected());

                cb2.setSelected(!cb1.isSelected());
            }
        });

        // Change column selection allowed state
        cb2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                table.setColumnSelectionAllowed(cb2.isSelected());
                table.setRowSelectionAllowed(!cb2.isSelected());
                cb1.setSelected(!cb2.isSelected());
            }
        });

        // Enable cell selection
        cb3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                table.setCellSelectionEnabled(cb3.isSelected());
                table.setRowSelectionAllowed(cb3.isSelected());
                table.setColumnSelectionAllowed(cb3.isSelected());
            }
        });

        control.add(cb1);
        control.add(cb2);
        control.add(cb3);

        add(pane, BorderLayout.CENTER);
        add(control, BorderLayout.SOUTH);
    }

    private class RowColumnListSelectionListener implements ListSelectionListener {
        public void valueChanged(ListSelectionEvent e) {
            if (table.getRowSelectionAllowed() &&
                !table.getColumnSelectionAllowed()) {
                int[] rows = table.getSelectedRows();
                System.out.println("Selected Rows: " + Arrays.toString(rows));
            }
            if (table.getColumnSelectionAllowed() &&
                !table.getRowSelectionAllowed()) {
                int[] cols = table.getSelectedColumns();
                System.out.println("Selected Columns: " + Arrays.toString(cols));
            } else if (table.getCellSelectionEnabled()) {
                int selectionMode = table.getSelectionModel().getSelectionMode();
                System.out.println("selectionMode = " + selectionMode);
                if (selectionMode == ListSelectionModel.SINGLE_SELECTION) {
                    int rowIndex = table.getSelectedRow();
                    int colIndex = table.getSelectedColumn();
                    System.out.printf("Selected [Row,Column] = [%d,%d]\n", rowIndex, colIndex);
                } else if (selectionMode == ListSelectionModel.SINGLE_INTERVAL_SELECTION ||
                    selectionMode == ListSelectionModel.MULTIPLE_INTERVAL_SELECTION) {
                    int rowIndexStart = table.getSelectedRow();
                    int rowIndexEnd = table.getSelectionModel().getMaxSelectionIndex();
                    int colIndexStart = table.getSelectedColumn();
                    int colIndexEnd = table.getColumnModel().getSelectionModel().getMaxSelectionIndex();

                    for (int i = rowIndexStart; i <= rowIndexEnd; i++) {
                        for (int j = colIndexStart; j <= colIndexEnd; j++) {
                            if (table.isCellSelected(i, j)) {
                                System.out.printf("Selected [Row,Column] = [%d,%d]\n", i, j);
                            }
                        }
                    }
                }
            }
        }
    }

    private static void showFrame() {
        JPanel panel = new JTableGetSelectedCells();
        panel.setOpaque(true);

        JFrame frame = new JFrame("JTable Selected Cells Demo");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

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

    class PremiereLeagueTableModel extends AbstractTableModel {
        // TableModel's column names
        private String[] columnNames = {
            "TEAM", "P", "W", "D", "L", "GS", "GA", "GD", "PTS"
        };

        // TableModel's data
        private Object[][] data = {
            { "Liverpool", 3, 3, 0, 0, 7, 0, 7, 9 },
            { "Tottenham", 3, 3, 0, 0, 8, 2, 6, 9 },
            { "Chelsea", 3, 3, 0, 0, 8, 3, 5, 9 },
            { "Watford", 3, 3, 0, 0, 7, 2, 5, 9 },
            { "Manchester City", 3, 2, 1, 0, 9, 2, 7, 7 }
        };

        public int getRowCount() {
            return data.length;
        }

        public int getColumnCount() {
            return columnNames.length;
        }

        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }

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

When you run the program you will see the following screen. Selecting some cells in the JTable will print the selected rows, the selected columns or some indexes of selected rows and columns in ListSelectionModel.MULTIPLE_INTERVAL_SELECTION selection mode.

JTable Get The Selected Cells

How do I programmatically select JTable’s rows?

This program shows you how to select some rows in the JTable programmatically. Below we demonstrates how to select rows using the setRowSelectionInterval() method, remove or clear row selection using removeRowSelectionInterval() method and use the addRowSelectionInterval() to add more rows to the previously selected rows.

package org.kodejava.example.swing;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class JTableRowSelectProgrammatically extends JPanel {
    public JTableRowSelectProgrammatically() {
        initializePanel();
    }

    private void initializePanel() {
        setLayout(new BorderLayout());
        setPreferredSize(new Dimension(475, 250));

        final JTable table = new JTable(new MyTableModel());
        table.setFillsViewportHeight(true);
        JScrollPane pane = new JScrollPane(table);

        JLabel label1 = new JLabel("From row: ");
        final JTextField field1 = new JTextField(3);
        JLabel label2 = new JLabel("To row: ");
        final JTextField field2 = new JTextField(3);
        JButton select = new JButton("Select");
        JButton clear = new JButton("Clear");
        JButton add = new JButton("Add another one");

        // Enables row selection mode and disable column selection
        // mode.
        table.setRowSelectionAllowed(true);
        table.setColumnSelectionAllowed(false);

        // Select rows based on the input.
        select.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                int index1 = 0;
                int index2 = 0;
                try {
                    index1 = Integer.valueOf(field1.getText());
                    index2 = Integer.valueOf(field2.getText());
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }

                if (index1 < 0 || index2 < 0 ||
                    index1 >= table.getRowCount() ||
                    index2 >= table.getRowCount()) {
                    JOptionPane.showMessageDialog(table, "Selection out of range!");
                } else {
                    table.setRowSelectionInterval(index1, index2);
                }
            }
        });

        // Clears row selection
        clear.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                table.removeRowSelectionInterval(0, table.getRowCount() - 1);
                field1.setText("");
                field2.setText("");
            }
        });

        // Add one more row after the last selected row.
        add.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                int index2 = 0;
                try {
                    index2 = Integer.valueOf(field2.getText());
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }

                index2 = index2 + 1;
                table.addRowSelectionInterval(index2, index2);
                field2.setText(String.valueOf(index2));
            }
        });

        JPanel command = new JPanel(new FlowLayout());
        command.add(label1);
        command.add(field1);
        command.add(label2);
        command.add(field2);
        command.add(select);
        command.add(clear);
        command.add(add);

        add(pane, BorderLayout.CENTER);
        add(command, BorderLayout.SOUTH);
    }

    public static void showFrame() {
        JPanel panel = new JTableRowSelectProgrammatically();
        panel.setOpaque(true);

        JFrame frame = new JFrame("JTable Row Selection");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

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

    public class MyTableModel extends AbstractTableModel {
        private String[] columns = {"ID", "NAME", "AGE", "A STUDENT?"};
        private Object[][] data = {
            {1, "Alice", 20, Boolean.FALSE},
            {2, "Bob", 10, Boolean.TRUE},
            {3, "Carol", 15, Boolean.TRUE},
            {4, "Ignasia", 20, Boolean.TRUE},
            {5, "Mallory", 25, Boolean.FALSE}
        };

        public int getRowCount() {
            return data.length;
        }

        public int getColumnCount() {
            return columns.length;
        }

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

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

        // 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 check box. A
        // number value is right aligned.
        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return data[0][columnIndex].getClass();
        }
    }
}

Below is the screen capture of the program.

Programmatically Select JTable Rows

How do I set the JTable’s selection mode?

There are three selection modes available in the JTable component. The selection mode can be a single selection, a single interval selection or a multiple interval selection. To set the selection mode we call the JTable.setSelectionMode() method and pass one of the following value as the parameter:

  • ListSelectionModel.SINGLE_SELECTION
  • ListSelectionModel.SINGLE_INTERVAL_SELECTION
  • ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
package org.kodejava.example.swing;

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

public class TableSelectionModeDemo extends JPanel {
    public TableSelectionModeDemo() {
        initializePanel();
    }

    private void initializePanel() {
        this.setLayout(new BorderLayout());

        JTable table = new JTable(new PremiereLeagueTableModel());

        // Settings table selection mode. We can use the following
        // three constants to define the selection mode.
        //
        // - ListSelectionModel.SINGLE_SELECTION
        // - ListSelectionModel.SINGLE_INTERVAL_SELECTION
        // - ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
        table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        JScrollPane pane = new JScrollPane(table);
        this.add(pane, BorderLayout.CENTER);
        this.setPreferredSize(new Dimension(500, 150));
    }

    public static void showFrame() {
        JPanel panel = new TableSelectionModeDemo();
        panel.setOpaque(true);

        JFrame frame = new JFrame("JTable Single Selection");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

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

    class PremiereLeagueTableModel extends AbstractTableModel {
        // TableModel's column names
        private String[] columnNames = {
            "TEAM", "P", "W", "D", "L", "GS", "GA", "GD", "PTS"
        };

        // TableModel's data
        private Object[][] data = {
            { "Liverpool", 3, 3, 0, 0, 7, 0, 7, 9 },
            { "Tottenham", 3, 3, 0, 0, 8, 2, 6, 9 },
            { "Chelsea", 3, 3, 0, 0, 8, 3, 5, 9 },
            { "Watford", 3, 3, 0, 0, 7, 2, 5, 9 },
            { "Manchester City", 3, 2, 1, 0, 9, 2, 7, 7 }
        };

        public int getRowCount() {
            return data.length;
        }

        public int getColumnCount() {
            return columnNames.length;
        }

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

JTable Selection Mode Demo

How do I allow row or column selection in JTable?

To allow a row selection or a column selection or both row and column selection in JTable component we can turn it on and off by calling the JTable‘s setRowSelectionAllowed() and JTable‘s setColumnSelectionAllowed() methods.

Both of these method accept a boolean value indicating whether the selection is allowed or not allowed. Setting both of them to true allow us to select rows and columns from JTable.

package org.kodejava.example.swing;

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

public class TableAllowColumnSelection extends JPanel {
    public TableAllowColumnSelection() {
        initializePanel();
    }

    private void initializePanel() {
        this.setLayout(new BorderLayout());
        this.setPreferredSize(new Dimension(500, 150));

        JTable table = new JTable(new PremiereLeagueTableModel());
        // sets to false to disallow row selection in the table
        // model.
        table.setRowSelectionAllowed(false);

        // Sets to true to allow column selection in the table
        // model.
        table.setColumnSelectionAllowed(true);

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

    public static void showFrame() {
        JPanel panel = new TableAllowColumnSelection();
        panel.setOpaque(true);

        JFrame frame = new JFrame("JTable Column Selection");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

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

    class PremiereLeagueTableModel extends AbstractTableModel {
        // TableModel's column names
        private String[] columnNames = {
            "TEAM", "P", "W", "D", "L", "GS", "GA", "GD", "PTS"
        };

        // TableModel's data
        private Object[][] data = {
            { "Liverpool", 3, 3, 0, 0, 7, 0, 7, 9 },
            { "Tottenham", 3, 3, 0, 0, 8, 2, 6, 9 },
            { "Chelsea", 3, 3, 0, 0, 8, 3, 5, 9 },
            { "Watford", 3, 3, 0, 0, 7, 2, 5, 9 },
            { "Manchester City", 3, 2, 1, 0, 9, 2, 7, 7 }
        };

        public int getRowCount() {
            return data.length;
        }

        public int getColumnCount() {
            return columnNames.length;
        }

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

JTable Row and Column Selection

How do I set or change JTable column width?

Each column of a JTable component is represented by the TableColumn class. The method for setting or changing the width of the column includes the setMinWidth(), setMaxWidth() and setPreferredWidth(). These methods is used to set the minimum, maximum and the preferred width of the column respectively.

When we set only the preferred width of a table column and the container get resized the preferred width will be used to recalculate the new column width to fill the available space, but the preferred width value itself does not change.

TableColumn object of a table can be obtained by calling table’s getColumnModel() method which return an instance of TableColumnModel. After having the TableColumModel in hand we can get the table’s column by calling the getColumn(int index) method and passes the index of the column.

package org.kodejava.example.swing;

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

public class TableColumnWidthDemo extends JPanel {
    public TableColumnWidthDemo() {
        initializePanel();
    }

    private void initializePanel() {
        // Defines table's column names.
        String[] columnNames = {
            "TEAM", "P", "W", "D", "L", "GS", "GA", "GD", "PTS"
        };

        // Defines table's data.
        Object[][] data = {
            { "Liverpool", 3, 3, 0, 0, 7, 0, 7, 9 },
            { "Tottenham", 3, 3, 0, 0, 8, 2, 6, 9 },
            { "Chelsea", 3, 3, 0, 0, 8, 3, 5, 9 },
            { "Watford", 3, 3, 0, 0, 7, 2, 5, 9 },
            { "Manchester City", 3, 2, 1, 0, 9, 2, 7, 7 }
        };

        // Defines table's column width.
        int[] columnsWidth = {
            200, 25, 25, 25, 25, 25, 25, 25, 50
        };

        // Creates an instance of JTable and fill it with data and
        // column names information.
        JTable table = new JTable(data, columnNames);

        // Configures table's column width.
        int i = 0;
        for (int width : columnsWidth) {
            TableColumn column = table.getColumnModel().getColumn(i++);
            column.setMinWidth(width);
            column.setMaxWidth(width);
            column.setPreferredWidth(width);
        }

        JScrollPane scrollPane = new JScrollPane(table);
        table.setFillsViewportHeight(true);
        this.setLayout(new BorderLayout());
        this.add(scrollPane, BorderLayout.CENTER);
        this.setPreferredSize(new Dimension(500, 200));
    }

    public static void showFrame() {
        JPanel panel = new TableColumnWidthDemo();
        panel.setOpaque(true);

        // Creates and configures the JFrame component for our
        // program.
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.setTitle("English Premiere League - 2018/2019");
        frame.pack();
        frame.setVisible(true);
    }

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

Here is the table created by the program above:

JTable Column Width Demo