Home > Java > javaTutorial > How to Refresh the Background Color of a Row in a JTable?

How to Refresh the Background Color of a Row in a JTable?

DDD
Release: 2024-11-22 07:23:11
Original
1051 people have browsed it

How to Refresh the Background Color of a Row in a JTable?

Refreshing Background Color for a Row in JTable

Issue:
When attempting to refresh the background color of a row in a JTable, it only works on the first iteration and fails subsequently.

Solution:

The issue arises because the setRowColor method in the ColorTable class is not resetting the background color for subsequent rows. To resolve this, the code should be modified as follows:

public void resetColor(Color color) {
    for (int i = 0; i < this.getRowCount(); i++) {
        // Reset all rows to the specified color
        this.setRowColor(i, color);
    }
}
Copy after login

In addition, to prevent the selected rows from being colored, the following line should be added within the prepareRenderer method:

if (rowSelection != null &amp;&amp; isRowSelected(row)) {
    continue;
}
Copy after login

This ensures that selected rows maintain their default background color.

Example Code:

// Import necessary libraries...

public class ColorTable extends JTable {

    private static final long serialVersionUID = 1L;
    private Map rowColor = new HashMap();
    private Map columnColor = new HashMap();
    private Color cellColor;
    private Color defaultColor;

    public ColorTable(TableModel model) {
        super(model);
    }

    public void setRowColor(int row, Color c) {
        rowColor.put(new Integer(row), c);
    }

    // ... Other methods remain the same ...

    @Override
    public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {

        Component c = super.prepareRenderer(renderer, row, column);
        if (defaultColor == null) {
            defaultColor = c.getBackground();
        }

        // Color order is as follows:
        // rowSelection, checkBox toggle for row color, column color, cell color
        if (rowSelection != null &amp;&amp; isRowSelected(row)) {
            continue;
        }

        // ...

        return c;
    }

    // ... Other methods remain the same ...

}

// ... Other code remains the same ...
Copy after login

The above is the detailed content of How to Refresh the Background Color of a Row in a JTable?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template