Search code examples
javaswingjtabletablecellrenderertablecelleditor

JTable with different row types


I want to implement a JTable in my program which has mulitple type different rows.

Here is an example:

enter image description here

So basically costs are calculated like that:

Sale * Production * Production % = Costs

What I am totally unsure is: How to give each row in the JTable model a new "type" of column. At the moment I am using the JTable model like that:

public Object getValueAt(int row, int col) {
        Customer cd = customerList.get(row);
        switch (col) {
        case 0:
            return cd.getName();
        case 1:
            return cd.getAge(); 
        case 2:
            return cd.getPhone(); 
        default:
            break;
        }

        return null;
    }

Any recommendations how to implement this use case?

I appreciate your answer!


Solution

  • If you want the cells in a row have a special formatting or data type just do what you did for Customer and just switch column and row, i.e. I assume one entry in your table is represented by a single column.

    Thus just do something like this:

    Report report = reports.get(col - 1); //made those names up but you should get the idea
    switch (row) {
      ...
      case 5:
        double p = report.getPercentage(); //assuming 10% is stored as 0.1
        return String.format("%.0f%%", p * 100); //%.0f means a floating point number with 0 fraction digits
      ...
    }
    

    Alternatively (esp. if your model needs to be more flexible or you just have a bunch of values, e.g. as a 2D array) store the type (i.e. how to display the value) in a map with either row, column or cell (row and column) index as key.

    Update:

    As mKorbel said in a comment, you'd better let the renderer do the formatting. The problem, however, is that you can't just register a renderer per row, so you'd have to come up with another solution.

    Two of them pop into my head right now:

    1. Subclass JTable in order to override getCellRenderer(row, col) in order to provide a PercentageCellRenderer for the row that needs it. You'd have to configure which row that is, e.g. in the table model.

    2. Provide a standard cell renderer which checks the row and column in getTableCellRendererComponent() and applies the formatting accordingly.