Java swing – JTable – Sub-tables / grouping – can it be done?

Maybe I’m not looking hard enough, but i’m having trouble finding a Java swing table example that has sub-groups.

Something Like:

| Table header 1 | Table header 2 | Table header 3 |
| Group A |
| Group A Col11 | | Group A Col12 | | Group A Col13 | 
| Group A Col21 | | Group A Col22 | | Group A Col23 | 
| Group B |
| Group B Col11 | | Group B Col2 | | Group A Col3 | 
....

Can this sort of thing be done with Java Swing tables?

Answer

First, let’s set up a simple Java Swing JTable test.

Simple JTable Test 1

With the data arranged like this, all we have to do is change the duplicate Group data values to spaces.

Simple JTable Test 2

We do that by creating a table model for the JTable.

First, here’s the code to create the JFrame.

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;

public class JTableFrame implements Runnable {

    @Override
    public void run() {
        JFrame frame = new JFrame("JTable Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JTableModel model = new JTableModel();
        JTable table = new JTable(model.getModel());
        JScrollPane scrollPane = new JScrollPane(table);
        frame.add(scrollPane);

        frame.setLocationByPlatform(true);
        frame.pack();
        frame.setVisible(true);
    }

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

Next, here’s the code to create the table model. I used a hard coded data source. You would probably get the data from somewhere.

import javax.swing.table.DefaultTableModel;

public class JTableModel {

    private DefaultTableModel model;

    private String[] columns = {"Group", "Alpha", "Beta", "Gamma"};

    private String[][] rows = {{"Group A", "all", "box", "game"},
            {"Group A", "apple", "band", "going"},
            {"Group B", "alabaster", "banquet", "ghost"},
            {"Group B", "alone", "boy", "ghoulish"}};

    public JTableModel() {
        this.model = new DefaultTableModel();
        this.model.setColumnIdentifiers(columns);
        setModelRows();
    }

    private void setModelRows() {
        String prevGroup = "";
        for (String[] row : rows) {
            if (row[0].equals(prevGroup)) {
                row[0] = " ";
            } else {
                prevGroup = row[0];
            }
            this.model.addRow(row);
        }
    }

    public DefaultTableModel getModel() {
        return model;
    }

}

Leave a Reply

Your email address will not be published. Required fields are marked *