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

How do I create a table model for JTable component?

Another way to create and configure a JTable component is using a table model. A table model is more preferred to using array or vector as the data source for the table.

The simplest way to create a table model is by extending the AbstractTableModel abstract class which implements the TableModel interface. The AbstractTableModel implements the standard behaviour of a table model. It implements almost all the methods of the TableModel interface, except three methods.

These three methods are the getValueAt(int rowIndex, int columnIndex) method, the getRowCount() method and the getColumnCount() method. The code below show you how to create a table model.

package org.kodejava.swing;

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

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

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

        JFrame frame = new JFrame("Premiere League - Season 2021-2022");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

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

    private void initializePanel() {
        // Creates an instance of PremiereLeagueTableModel
        PremiereLeagueTableModel tableModel = new PremiereLeagueTableModel();

        // Creates an instance of JTable with a TableModel
        // as the constructor parameters.
        JTable table = new JTable(tableModel);
        table.setFillsViewportHeight(true);
        TableColumnModel columnModel = table.getColumnModel();
        columnModel.getColumn(0).setPreferredWidth(200);

        JScrollPane scrollPane = new JScrollPane(table);

        this.setPreferredSize(new Dimension(500, 500));
        this.setLayout(new BorderLayout());
        this.add(scrollPane, 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}
        };

        /**
         * Returns the number of rows in the table model.
         */
        public int getRowCount() {
            return data.length;
        }

        /**
         * Returns the number of columns in the table model.
         */
        public int getColumnCount() {
            return columnNames.length;
        }

        /**
         * Returns the column name for the column index.
         */
        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }

        /**
         * Returns data type of the column specified by its index.
         */
        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return getValueAt(0, columnIndex).getClass();
        }

        /**
         * Returns the value of a table model at the specified
         * row index and column index.
         */
        public Object getValueAt(int rowIndex, int columnIndex) {
            return data[rowIndex][columnIndex];
        }
    }
}
JTable TableModel Demo

JTable TableModel Demo

How do I create a simple JTable component?

The code snippet presented below shows you how to create a simple JTable component in a swing application. To create a JTable component we initialize it using the constructor that accept two parameters.

The first parameter is the table’s row of data which type is Object[][], a two-dimensional array of Object. The second parameter is the table’s column names which type is Object[], an array of object.

After the JTable instance is created we place it inside a scroll pane component which in turn is added to the frame’s content pane.

package org.kodejava.swing;

import javax.swing.*;
import java.awt.*;
import java.text.MessageFormat;
import java.util.Calendar;

public class SimpleJTableDemo extends JFrame {
    public SimpleJTableDemo() throws HeadlessException {
        initializeUI();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new SimpleJTableDemo().setVisible(true));
    }

    private void initializeUI() {
        // Defines table's column names.
        String[] columnNames = {
                "ID", "Name", "Date of Birth", "Sex"
        };

        // Defines table's data.
        Object[][] rowData = {
                {1, "Alice", createDOB(1980, Calendar.JANUARY, 1), "F"},
                {2, "Bob", createDOB(1982, Calendar.JUNE, 21), "M"},
                {3, "Carol", createDOB(1970, Calendar.OCTOBER, 12), "M"},
                {4, "Mallory", createDOB(1988, Calendar.FEBRUARY, 19), "M"}
        };

        // Initializes an instance of JTable and specifies the table
        // data and column names. Then we place the table in a scroll pane.
        JTable table = new JTable(rowData, columnNames);
        JScrollPane pane = new JScrollPane(table);

        // Sets the frame setting.
        setTitle("Simple JTable Demo");
        setSize(new Dimension(500, 500));
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        getContentPane().add(pane, BorderLayout.CENTER);
    }

    private String createDOB(int year, int month, int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, day);
        return MessageFormat.format("{0,date,dd-MMM-yyyy}", calendar.getTime());
    }
}

When we run the program we will see the following result:

Simple JTable Demo

Simple JTable Demo

How do I break a paragraph into sentences?

This example show you how to use the BreakIterator.getSentenceInstance() to breaks a paragraphs into sentences that composes the paragraph. To get the BreakIterator instance we call the getSentenceInstance() factory method and passes a locale information.

In the count(BreakIterator bi, String source) method we iterate the break to extract sentences that composes the paragraph which value is stored in the paragraph variable.

package org.kodejava.text;

import java.text.BreakIterator;
import java.util.Locale;

public class BreakSentenceExample {
    public static void main(String[] args) {
        String paragraph = """
                Line boundary analysis determines where a text \
                string can be broken when line-wrapping. The \
                mechanism correctly handles punctuation and \
                hyphenated words. Actual line breaking needs to \
                also consider the available line width and is \
                handled by higher-level software.
                """;

        BreakIterator iterator = BreakIterator.getSentenceInstance(Locale.US);

        int sentences = count(iterator, paragraph);
        System.out.println("Number of sentences: " + sentences);
    }

    private static int count(BreakIterator bi, String source) {
        int counter = 0;
        bi.setText(source);

        int lastIndex = bi.first();
        while (lastIndex != BreakIterator.DONE) {
            int firstIndex = lastIndex;
            lastIndex = bi.next();

            if (lastIndex != BreakIterator.DONE) {
                String sentence = source.substring(firstIndex, lastIndex);
                System.out.println("sentence = " + sentence);
                counter++;
            }
        }
        return counter;
    }
}

Our program will print the following result on the console screen:

sentence = Line boundary analysis determines where a text string can be broken when line-wrapping. 
sentence = The mechanism correctly handles punctuation and hyphenated words. 
sentence = Actual line breaking needs to also consider the available line width and is handled by higher-level software.

Number of sentences: 3

How do I break a text or sentence into words?

At first, it might look simple. We can just split the text using the String.split(), the word is split using space. But what if a word ends with questions marks (?) or exclamation marks (!) instead? There might be some other rules that we also need to care.

Using the java.text.BreakIterator makes it much simpler. The class’s getWordInstance() factory method creates a BreakIterator instance for words break. Instantiating a BreakIterator and passing a locale information makes the iterator to breaks the text or sentence according the rule of the locale. This is really helpful when we are working with a complex language such as Japanese or Chinese.

Let us see an example of using the BreakIterator below.

package org.kodejava.text;

import java.text.BreakIterator;
import java.util.Locale;

public class BreakIteratorExample {
    public static void main(String[] args) {
        String data = "The quick brown fox jumps over the lazy dog.";
        String search = "dog";

        // Gets an instance of BreakIterator for word break for the
        // given locale. We can instantiate a BreakIterator without
        // specifying the locale. The locale is important when we
        // are working with languages like Japanese or Chinese where
        // the breaks standard may be different compared to English.
        BreakIterator bi = BreakIterator.getWordInstance(Locale.US);

        // Set the text string to be scanned.
        bi.setText(data);

        // Iterates the boundary / breaks
        System.out.println("Iterates each word: ");
        int count = 0;
        int lastIndex = bi.first();
        while (lastIndex != BreakIterator.DONE) {
            int firstIndex = lastIndex;
            lastIndex = bi.next();

            if (lastIndex != BreakIterator.DONE
                    && Character.isLetterOrDigit(data.charAt(firstIndex))) {
                String word = data.substring(firstIndex, lastIndex);
                System.out.printf("'%s' found at (%s, %s)%n",
                        word, firstIndex, lastIndex);

                // Counts how many times the word dog occurs.
                if (word.equalsIgnoreCase(search)) {
                    count++;
                }
            }
        }

        System.out.println("Number of word '" + search + "' found = " + count);
    }
}

Here are the program output:

Iterates each word: 
'The' found at (0, 3)
'quick' found at (4, 9)
'brown' found at (10, 15)
'fox' found at (16, 19)
'jumps' found at (20, 25)
'over' found at (26, 30)
'the' found at (31, 34)
'lazy' found at (35, 39)
'dog' found at (40, 43)
Number of word 'dog' found = 1