The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.swing.table  [62 examples] > Cells  [5 examples]

e929. Creating a Class-Based Custom Cell Renderer in a JTable Component

See e928 Creating a Custom Cell Renderer in a JTable Component for information on how to implement a custom table cell renderer.

There are two ways to associate a custom table cell renderer with a column. The first is to explicitly assign the renderer to the column; the example cited above demonstrates this method. The second is to associate the renderer with a type; this example demonstrates this method. The example installs a renderer for values of the type Color.

    DefaultTableModel model = new DefaultTableModel() {
        // This method returns the Class object of the first
        // cell in specified column in the table model.
        // Unless this method is overridden, all values are
        // assumed to be the type Object.
        public Class getColumnClass(int mColIndex) {
            int rowIndex = 0;
            Object o = getValueAt(rowIndex, mColIndex);
            if (o == null) {
                return Object.class;
            } else {
                return o.getClass();
            }
        }
    };
    JTable table = new JTable(model);
    
    // Add data
    model.addColumn("Col1", new Object[]{Color.red});
    model.addRow(new Object[]{Color.green});
    model.addRow(new Object[]{Color.blue});
    
    table.setDefaultRenderer(Color.class, new ColorTableCellRenderer());
    
    public class ColorTableCellRenderer extends JComponent implements TableCellRenderer {
        // The current color to display
        Color curColor;
    
        public Component getTableCellRendererComponent(JTable table, Object value,
                boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex) {
            // Set the color to paint
            if (curColor instanceof Color) {
                curColor = (Color)value;
            } else {
                // If color unknown, use table's background
                curColor = table.getBackground();
            }
            return this;
        }
    
        // Paint current color
        public void paint(Graphics g) {
            g.setColor(curColor);
            g.fillRect(0, 0, getWidth()-1, getHeight()-1);
        }
    }

 Related Examples
e926. Getting and Setting a Cell Value in a JTable Component
e927. Using Built-In Cell Renderers and Editors in a JTable Component
e928. Creating a Custom Cell Renderer in a JTable Component
e930. Copying Cell Values to the Clipboard from a JTable Component

See also: Column Heads    Columns    Editing    Events    Layout    Rows    Scrolling    Selection    Sorting    Table Model    Tool Tips   


© 2002 Addison-Wesley.