Thursday, June 13, 2019

change java swing table cell color

changing  java swing table cell color according to cell value


Recently i wanted to change cell color of a jTable cell according to value it contains.this is the soulution i came up with.


This is acquired by using custom cell renderer class and overriding getTableCellRendererComponent method.

inner class :

class MyTableCellRenderer extends DefaultTableCellRenderer {

    @Override
    public Color getBackground() {
        return super.getBackground();
    }
}





adding the color change :

 public void changeTable(JTable table, int column_index) {
        table.getColumnModel().getColumn(column_index).setCellRenderer(new DefaultTableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                int st_val = Integer.parseInt(table.getValueAt(row, 2).toString());
                int req_val = 2000;
                if (st_val < req_val) {
                    c.setBackground(Color.MAGENTA);
                } else {
                    c.setBackground(Color.GREEN);
                }
                return c;
            }
        });
    }


to scroll down to the added row i have added component listner and a component adaptor.


in action : https://www.youtube.com/watch?v=GD5J25I56xA


github : https://github.com/stark9000/jTable_cell_color



No comments:

Post a Comment