문제

I have written a default table render as follows:

public class CustTableRenderer extends DefaultTableCellRenderer{

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
        Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
        try {

            Object cellObj = table.getModel().getValueAt(row, 7); 
            double cellValue = (Double) cellObj;

            if (cellValue < 0) {
                comp.setBackground(new Color(255, 48, 48));
            } else if (cellValue == 0) {
                comp.setBackground(new Color(173, 255, 47));
            } else {
                comp.setBackground(Color.white);
            }

            if (isSelected) {
                comp.setBackground(new Color(71, 60, 139));
                TableModel model = table.getModel();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return comp;
    }
}

To highlight the rows which contain minus values of column 7, I have also set setAutoCreateRowSorter to true. My problem is when I click a header to sort according to it table is sorted but the highlighted row is not changed, therefore a wrong row is highlighted.

How to redraw the table when it is sorted?

도움이 되었습니까?

해결책

the coordinates passed into the renderer are in view coordinate system, you have to convert them to model coordinates before accessing the model:

  int modelRow = table.convertRowIndexToModel(row);
  int modelColumn = table.convertColumnIndexToModel(column);
  cellObject = table.getModel().getValueAt(modelRow, modelColumn);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top