简体   繁体   中英

How to change the jTable cell color with CustomRenderer

My problem is that I want to change the individual background color of a cell in one column in a jTable. The code I have come up with changes the color to one and it applies to all the columns. What am I doing wrong?

This is my code

public void fillReserveTable() {
    MemberDAO dao = DATA.MemberDAO.getInstance();
    ResultSet res2 = dao.fillReservationTable();
    try {
        if (res2.next()) {
            res2.beforeFirst();
            reserveTable.setModel(DbUtils.resultSetToTableModel(res2));
            setUpOnHold(reserveTable, reserveTable.getColumnModel().getColumn(4));
            reserveTable.getColumnModel().getColumn(3).setCellRenderer(new CustomRenderer());
            jScrollPane14.setVisible(true);
        }else{
            jScrollPane14.setVisible(false);
        }
    } catch (SQLException e) {
    }
}

class CustomRenderer extends DefaultTableCellRenderer {

    MemberDAO dao = DATA.MemberDAO.getInstance();
    ResultSet res2 = dao.fillReservationTable();

    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        Component cellComponent = super.getTableCellRendererComponent(reserveTable, value, isSelected, hasFocus, row, column);
        int row2 = 0;
        try {
            while (res2.next()) {
                String status = reserveTable.getValueAt(row2, 3).toString();
                if (status.equals("Available")) {
                    cellComponent.setBackground(Color.green);
                } else {
                    cellComponent.setBackground(Color.red);
                }
                row2++;
            }
        } catch (SQLException e) {
        }
        return cellComponent;
    }
}

Cell rendering happens very frequently. You don't want to execute an SQL call as part of your rendering. Also, you should log the SQLException when it happens instead of silently swallowing it.

In this case, you're storing a result set as a field in the cell renderer. The first time you render, you iterate to the end of the result set.

Instead of querying for the status, use the value parameter which is passed to the renderer. This will be the value in the cell being rendered. If you need some other cell's value, get it from the TableModel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM