Cell Renderers


Overview Basic version Model Cell Renderer Editor Column widths Tooltips Controls in cells

The cells of a table are drawn by an instance of a cell renderer class. This needs to implement the TableCellRenderer interface. This has just one method - getTableCellRendererComponent - which should return a component which can be used to display the cell.

A table can have different renderers for displaying different data types, or you can set a renderer for a specifies column. To display a String, a JLabel is an appropriate component to display.

For example, we will produce this:

We need to define a class which implements TableCellRenderer, and set an instance as the renderer of Strings for our table.

Our renderer is:

 
class MyRenderer extends JLabel implements TableCellRenderer {
// create fonts and colours

    static Color color1 = new Color(230, 255, 255);
    static Color color2 = new Color(220, 240, 255);
    static Font font = new Font("Ubuntu", Font.BOLD, 14);

    MyRenderer() {
        setFont(font);
        setHorizontalAlignment(SwingConstants.CENTER);
        setOpaque(true); // else we don't see background
    }

    public Component getTableCellRendererComponent(JTable table, Object value, 
     boolean isSelected, boolean hasFocus, int row, int column) {
        setText((String) value); // value is from the data model
        if (row % 2 == 0) { // even numbered rows
            setBackground(color1);
        } else { // odd rows in different colour
            setBackground(color2);
        }
        return this; // 'this' is a JLabel, suitable to display text
    }

}

And we set the renderer and format the header by


        table.setDefaultRenderer(String.class, new MyRenderer());
        JTableHeader header = table.getTableHeader();
        header.setBackground(Color.black);
        header.setForeground(Color.white);
        Font font = new Font("Ubuntu", Font.BOLD, 16);
        header.setFont(font);

            

We have set this to be the renderer for teh table to use for String.class data.

Comments

0 responses so far

Add a new comment

Your name

Your email (will not be published)

Your comment (no HTML)

Are you a robot? Please type the two words: