My Java 8 applet connects to an SQL database and displays the result of a "select" statement in a JTable
with two columns:
If the String in row 1/ColumnA isn't the same as the String in row 0/ColumnA, I want to give row 1 a grey background color (to mark the start of "new" data), the other rows should use the default white color.
Code for creating the table:
JTable myTable = new JTable();
myTable.setSelectionModel(new ToggleListSelectionModel()); //custom selection model
myTable.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"ColumnA", "ColumnB"
}
));
Getting the data and filling the table:
Statement stat = connection.createStatement();
ResultSet rs = stat.executeQuery(someSelectStatement);
Object[] row = null;
while(rs.next()) {
int columns = rs.getMetaData().getColumnCount();
row = new Object[columns];
for (int i=1; i<=columns; i++) {
row[i - 1] = rs.getObject(i);
}
//TODO: Set color of row according to data in "ColumnA" of previous row
((DefaultTableModel) myTable.getModel()).insertRow(rs.getRow()-1,row); //Add new row with the ResultSet's content
//Get String data of ColumnA for this specific row with e.g. "(String) row[0]"
}
rs.close();
stat.close();
From what I've found so far, I have to use a custom TableModel
instead of the DefaultTableModel
I set in the beginning but how do I use it? Everything I've found uses fixed checks, e.g.
if content in the cell is 'buy', set the background color to 'green'
(e.g. here or here) but in my case I don't know anything about the content when the table is created because it's filled/rows are added at runtime.
I also found this answer but the author of the question reads the data, then changes the model and only then fills the table, while I fill the table row by row (directly after reading the row's content).
My question: I know how to compare the content of a cell to content of the cell in the previous row but how do I set the background color of the row at runtime?
Edit:
Here's some MRE code for filling the table. Please note: If you post a suggestion about how to accomplish what I want to do, keep in mind that I'm working with a database and a ResultSet
(see code above), not pre-defined data (see code below)!
JTable myTable = new JTable();
myTable.setSelectionModel(new ToggleListSelectionModel()); //custom selection model
myTable.setModel(new DefaultTableModel(
new Object[][] {
{"1000", 123},
{"1000", 234},
{"1001", 123},
{"1002", 123},
{"1002", 234},
{"1002", 345},
{"1003", 123},
{"1003", 234}
},
new String[] {
"ColumnA", "ColumnB"
}
));
Result:
Desired result (grey background for every new "Column A" value):
Alternative result (alternate marking all rows of a group):