Overview
This article demonstrates how to create a simple table to display strings, checkboxes and comboboxes.
Creating a table.
Firstly we need to create a table with some data in it. The table will contain three columns - a string, a checkbox and a combobox.
DefaultTableModel tableModel = new DefaultTableModel(); tableModel.setColumnCount(3); tableModel.addRow(new Object[] {new String("Row 0"), new CheckBox(), new ComboBox(new Object[] {new String("String 1"), new String("String 2"), new String("String 3") } ) } ); ... TableEx table = new TableEx(tableModel);
At this stage only the column containing the string will be displayed correctly as the default cell renderer will try to render the checkbox and combobox as strings.

Rendering a table.
To render the objects within the table correctly we need to create a custom cell renderer that determines what each of the objects should look like. This is a simple as checking what type the object is and casting it to the desired component, therefore using the components renderer to display it in the table.
table.setDefaultRenderer(Object.class, new TableCellRenderer() { public Component getTableCellRendererComponent(Table table, Object value, int column, int row) { if (value instanceof CheckBox) { return (CheckBox)value; } else if (value instanceof ComboBox) { return (ComboBox)value; } else if (value != null) { return new Label(value.toString()); } return new Label(); } });
Using the custom cell renderer the checkbox and combobox columns will be rendered correctly.


Add Comment