Java JTable change cell color

后端 未结 7 1541
说谎
说谎 2020-11-30 14:14

I would like to make an editable table and then check the data to make sure its valid. Im not sure how to change the color of just one cell. I would like to get a cell, for

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 14:33

    This is the simplest way to color a particular Column or cell in a jTable.

    First just create a simple class of CustomRenderer

    class CustomRenderer extends DefaultTableCellRenderer 
    { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); setForeground(Color.blue); > return c; } }

    This code gets the column of cell to render

    TableColumn col = tblExamHistoryAll.getColumnModel().getColumn(5);
    DefaultTableModel model3 = (DefaultTableModel)tblExamHistoryAll.getModel();
    col.setCellRenderer(new CustomRenderer());
    

    This is to clear all previous rows from your table. If you do not want them just remove these lines

    model3.getDataVector().removeAllElements();
    model3.fireTableDataChanged();
    

提交回复
热议问题