Category Archives: JTable

How to display line numbers in JTable

Its unfortunately that Java Swing does not include a feature to show the line number for each row on a JTable. This would be similar to the line numbers shown in a spreadsheet application. Fortunately, Swing’s flexibility and extensibility allows us to create one with ease.

Most of the solutions out there are based on using two tables side-by-side. One to represent the main table and the other to display the line numbers. There are event handlers listening on the main table to update the line number table.

I present another solution which is based on a single JComponent that will render the line numbers. This is lighter and more easily customizable in case you need to add additional features or behaviors.

READ MORE »

Stop hardcoding column numbers in your TableModel

If you always been using column numbers when implementing your TableModel, you’ll know that it a burden when you have to change the order of the columns.

If you normally do the following in your TableModel implementation:

    @Override public String getColumnName(int column) {
        switch(column) {
            case 0: return "Closing Date";
            case 1: return "Open Price";
            case 2: return "Day High";
            case 3: return "Day Low";
            case 4: return "Close< Price";
        }
        return null;
    }

You'll have to go through the source code and re-number each column whenever you need to change the order of the columns. There will be multiple places to update, such as the getColumnName and getValueAt methods. If you do complex rendering then you will also need to update the TableCellRenderer implementation as well.

To avoid hardcoding the column numbers, you can use enums. Enums are both more descriptive and have ordinal values.

READ MORE »

How to create a multi-line column header

If you didn’t already know, you can embed simple HTML inside all Swing text components including JLabel. The default renderer for a the column header is a JLabel component. In order to create a multiple row header, simply use HTML markup with a “<br>” HTML separating the rows.

READ MORE »