Question

I'm trying to color the text of every row in a table depending on one of the columns in the table. I'm having trouble grasping the concept of renderers, and I've tried out several different renderers but don't seem to understand what they do.

I am trying to load the top ten racers from a certain API given to us by our lecturer into the table model, but colouring each row based on the gender of the racer (which is returned by the getCategory() method of a Finisher/Racer object).

FYI, DataTable is an object written by our lecturer. It's basically a 2D array object.

public void showRacers(DefaultTableModel tblModel,
        @SuppressWarnings("rawtypes") JList listOfRaces) {
    // Clear the model of any previous searches
    tblModel.setRowCount(0);
    // Initialize an object to the selected city
    CityNameAndKey city = (CityNameAndKey) listOfRaces.getSelectedValue();
    // Get the runners for this city
    DataTable runners = this.getRunners(city);
    // Set the column headers
    this.setColumnHeaders(tblModel);
    // Make an array list of object Finisher
    ArrayList<Finisher> finisherList = new ArrayList<Finisher>();
    // Make an array that holds the data of each finisher
    Object[] finisherData = new Object[6];
    // Make a finisher object
    Finisher f;
    for (int r = 0; r < 10; r++) {
        // Assign the data to the finisher object
        finisherList.add(f = new Finisher(runners.getCell(r, 0), runners
                .getCell(r, 1), runners.getCell(r, 2), runners
                .getCell(r, 3), runners.getCell(r, 4), runners
                .getCell(r, 5)));
        // Add the data into the array
        finisherData[0] = f.getPosition();
        finisherData[1] = f.getBibNo();
        finisherData[2] = f.getTime();
        finisherData[3] = f.getGender();
        finisherData[4] = f.getCategory();
        finisherData[5] = f.getRuns();
        // Put it into the table model
        tblModel.addRow(finisherData);
    }
}

I would greatly appreciate an explanation, rather than just the answer to my question. Guidance to the answer would be great, and some code would be extremely helpful, but please no: "You should have written this: ten lines of code I don't get

Thank you very much! :)

Was it helpful?

Solution

Using a TableCellRenderer will only allow you to color one column. You would have to have one for each column. A much easier approach is to override prepareRenderer(...) in JTable to color an entire row.

See trashgod's answer here or camickr's answer here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top