Home >Java >javaTutorial >How to Refresh Background Color for a Row in JTable?
Refreshing background color for a row in JTable
When working with Swing JTables, it is possible to set the background color of individual rows using custom cell renderers. By implementing the prepareRenderer method in a renderer class, you can manipulate the background color based on specific conditions or user interactions.
Consider the following example:
public class ColorTable extends JTable { private static final long serialVersionUID = 1L; private Map<Integer, Color> rowColors = new HashMap<>(); @Override public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { Component c = super.prepareRenderer(renderer, row, column); if (!isRowSelected(row)) { Color color = rowColors.get(row); if (color != null) { c.setBackground(color); } else { c.setBackground(getDefaultRenderer(getColumnClass(column)).getBackground()); } } return c; } public void setRowColor(int row, Color color) { rowColors.put(row, color); } }
In this example, the ColorTable class extends JTable and allows you to specify different background colors for rows by calling the setRowColor method. This can be useful for visually indicating the status or importance of individual rows within the table.
Resetting row colors
To reset the background colors of all rows to a default color, you can use a method like the following:
public void resetRowColors(Color defaultColor) { rowColors.clear(); setBackground(defaultColor); }
Example usage:
// Create a ColorTable ColorTable table = new ColorTable(); // Add data to the table table.setModel(new DefaultTableModel(new Object[][], new String[]{})); // Set background color for specific rows table.setRowColor(0, Color.GREEN); table.setRowColor(1, Color.RED); // Reset row colors to default table.resetRowColors(Color.WHITE);
By implementing a custom cell renderer and providing methods to set and reset row colors, you can easily modify the appearance of JTable rows based on your specific requirements.
The above is the detailed content of How to Refresh Background Color for a Row in JTable?. For more information, please follow other related articles on the PHP Chinese website!