简体   繁体   English

如何使用CustomRenderer更改jTable单元格颜色

[英]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. 我的问题是我想在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. 您不希望在渲染过程中执行SQL调用。 Also, you should log the SQLException when it happens instead of silently swallowing it. 此外,您应该在SQLException发生时记录它,而不是静默吞咽它。

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. 不使用查询状态,而是使用传递给渲染器的value参数。 This will be the value in the cell being rendered. 这将是正在渲染的单元格中的值。 If you need some other cell's value, get it from the TableModel. 如果您需要其他单元格的值,请从TableModel获取它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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