javajtablerendererjxtable

Color Cell based on value


im using JXTable and trying to color the row based on value, BUT the show empty(but the render is running because it show the syso in console)

public class MyCellRenderer extends JLabel implements TableCellRenderer {
        public Component getTableCellRendererComponent(JTable table, Object value,
                boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex) {
            SimpleTableModel mymodel = (SimpleTableModel) jxtableListar.getModel(); 
            ModelProtocolo actualModel= (ModelProtocolo ) mymodel.getProtocolo(rowIndex) ;

            if(actualModel.getValue() > 0) {
                System.out.println("Yep the Render is working");

            }
                        return this;
        }
    }


jxtableListar.setDefaultRenderer(Object.class, new MyCellRenderer ());

i did not found any usefull "tutorial" how to use the JXTable renderer, since they talk about something about Hightlight, but all the tutorials are "out of information" to learn

is there any good way/tutorial to color a JXTable row base on a value of the cell?


Solution

  • Your renderer is returning a JLabel (itself) that hasn't had anything set on it. Instead, extend DefaultTableCellRenderer:

    public class MyCellRenderer extends DefaultTableCellRenderer {
        @override
        public Component getTableCellRendererComponent(JTable table, Object value,
                boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex) {
            SimpleTableModel mymodel = (SimpleTableModel) jxtableListar.getModel(); 
            ModelProtocolo actualModel= (ModelProtocolo ) mymodel.getProtocolo(rowIndex) ;
    
            JLabel label = (JLabel) super.getTableCellRendererComponent(/* pass in all params */);
            label.setText(/*whatever the text should be*/);
            label.setBackground(/*whatever the color should be*/);
            return label;
        }
    }