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

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

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

    public JTableGetSelectedCells() {
        initializePanel();
    }

    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(JTableGetSelectedCells::showFrame);
    }

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

        table = new JTable(new PremiereLeagueTableModel());
        table.getColumnModel().getColumn(0).setMinWidth(200);
        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(e -> {
            table.setRowSelectionAllowed(cb1.isSelected());
            table.setColumnSelectionAllowed(!cb1.isSelected());

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

        // Change column selection allowed state
        cb2.addActionListener(e -> {
            table.setColumnSelectionAllowed(cb2.isSelected());
            table.setRowSelectionAllowed(!cb2.isSelected());
            cb1.setSelected(!cb2.isSelected());
        });

        // Enable cell selection
        cb3.addActionListener(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);
    }

    static class PremiereLeagueTableModel extends AbstractTableModel {
        // TableModel's column names
        private final String[] columnNames = {
                "CLUB", "MP", "W", "D", "L", "GF", "GA", "GD", "PTS"
        };

        // TableModel's data
        private final Object[][] data = {
                {"Chelsea", 8, 6, 1, 1, 16, 3, 13, 19},
                {"Liverpool", 8, 5, 3, 0, 22, 6, 16, 18},
                {"Manchester City", 8, 5, 2, 1, 16, 3, 13, 17},
                {"Brighton", 8, 4, 3, 1, 8, 5, 3, 15},
                {"Tottenham", 8, 5, 0, 3, 9, 12, -3, 15}
        };

        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];
        }
    }

    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);
                            }
                        }
                    }
                }
            }
        }
    }
}

Run the program, and 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

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

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

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

    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(JTableRowSelectProgrammatically::showFrame);
    }

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

        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(event -> {
            int index1 = 0;
            int index2 = 0;
            try {
                index1 = Integer.parseInt(field1.getText());
                index2 = Integer.parseInt(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 - 1, index2 - 1);
            }
        });

        // Clears row selection
        clear.addActionListener(e -> {
            table.removeRowSelectionInterval(0, table.getRowCount() - 1);
            field1.setText("");
            field2.setText("");
        });

        // Add one more row after the last selected row.
        add.addActionListener(event -> {
            int index2 = 0;
            try {
                index2 = Integer.parseInt(field2.getText());
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

            index2 = index2 + 1;
            if (index2 <= table.getRowCount()) {
                table.addRowSelectionInterval(index2 - 1, index2 - 1);
                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);
    }

    static class MyTableModel extends AbstractTableModel {
        private final String[] columns = {"ID", "NAME", "AGE", "A STUDENT?"};
        private final Object[][] data = {
                {1, "Alice", 20, Boolean.FALSE},
                {2, "Bob", 10, Boolean.TRUE},
                {3, "Carol", 15, Boolean.TRUE},
                {4, "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

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

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

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

    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(TableSelectionModeDemo::showFrame);
    }

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

        JTable table = new JTable(new PremiereLeagueTableModel());
        TableColumnModel columnModel = table.getColumnModel();
        columnModel.getColumn(0).setPreferredWidth(200);

        // 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, 500));
    }

    static class PremiereLeagueTableModel extends AbstractTableModel {
        // TableModel's column names
        private final String[] columnNames = {
                "CLUB", "MP", "W", "D", "L", "GF", "GA", "GD", "PTS"
        };

        // TableModel's data
        private final Object[][] data = {
                {"Chelsea", 8, 6, 1, 1, 16, 3, 13, 19},
                {"Liverpool", 8, 5, 3, 0, 22, 6, 16, 18},
                {"Manchester City", 8, 5, 2, 1, 16, 3, 13, 17},
                {"Brighton", 8, 4, 3, 1, 8, 5, 3, 15},
                {"Tottenham", 8, 5, 0, 3, 9, 12, -3, 15}
        };

        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

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

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

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

    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(TableAllowColumnSelection::showFrame);
    }

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

        JTable table = new JTable(new PremiereLeagueTableModel());
        TableColumnModel columnModel = table.getColumnModel();
        columnModel.getColumn(0).setPreferredWidth(200);

        // setting to false disallow row selection in the table model
        table.setRowSelectionAllowed(false);

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

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

    static class PremiereLeagueTableModel extends AbstractTableModel {
        // TableModel's column names
        private final String[] columnNames = {
                "CLUB", "MP", "W", "D", "L", "GF", "GA", "GD", "PTS"
        };

        // TableModel's data
        private final Object[][] data = {
                {"Chelsea", 8, 6, 1, 1, 16, 3, 13, 19},
                {"Liverpool", 8, 5, 3, 0, 22, 6, 16, 18},
                {"Manchester City", 8, 5, 2, 1, 16, 3, 13, 17},
                {"Brighton", 8, 4, 3, 1, 8, 5, 3, 15},
                {"Tottenham", 8, 5, 0, 3, 9, 12, -3, 15}
        };

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

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

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

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return getValueAt(0, columnIndex).getClass();
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            return data[rowIndex][columnIndex];
        }
    }
}
JTable Row and Column Selection

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

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

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

    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("Premiere League - Season 2021-2022");
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(TableColumnWidthDemo::showFrame);
    }

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

        // Defines table's data.
        Object[][] data = {
                {"Chelsea", 8, 6, 1, 1, 16, 3, 13, 19},
                {"Liverpool", 8, 5, 3, 0, 22, 6, 16, 18},
                {"Manchester City", 8, 5, 2, 1, 16, 3, 13, 17},
                {"Brighton", 8, 4, 3, 1, 8, 5, 3, 15},
                {"Tottenham", 8, 5, 0, 3, 9, 12, -3, 15}
        };

        // 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, 500));
    }
}

Here is the table created by the program above:

JTable Column Width Demo

JTable Column Width Demo