tags:

views:

273

answers:

3

The following ListCellRenderer does not receive click events on the nested ComboBoxes. Do I need to enable something?

class FilterCellRenderer implements ListCellRenderer {

    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        Filter filter = (Filter)value;

        JPanel filterPanel = new JPanel();
        FlowLayout layout = new FlowLayout();
        layout.setAlignment(FlowLayout.LEFT);
        filterPanel.setLayout(layout);
        filterPanel.add(new JLabel(filter.getLabel()));

        final List<Object> options = filter.getOptions();
        if (options.size() > 1) {
            JComboBox optionCombo = new JComboBox(new AbstractComboBoxModel() {

                public int getSize() {
                    return options.size();
                }

                public Object getElementAt(int index) {
                    return options.get(index);
                }
            });
            optionCombo.setSelectedItem(filter.getValue());
            filterPanel.add(optionCombo);
        }

        if (isSelected) {
            filterPanel.setBackground(list.getSelectionBackground());
            filterPanel.setForeground(list.getSelectionForeground());
        } 
        return filterPanel;
    }

}
A: 

It's a little bit tricky this. I believe you need to replace the JList with a single column JTable. Then set a table cell editor as well as renderer. IIRC, there might be a problem losing the first click (which gets used to select that cell edited).

Also it's a very good idea to reuse the components between each call to getCellRendererComponent. The components are used as a stamp and then discarded. Performance will suck massively if they are recreated each time.

Tom Hawtin - tackline
+1  A: 

Renderer components in swing work like "rubber stamps" -they are just used to render/paint a value and are not added to the parent container in the usual way (just think how a single component could be added in multiple places!).

It sounds like you may want an editor rather than a renderer (an editor is a fully-fledged component, added in one place at any given time). Failing that you will have to install the MouseListener on the JList instead.

Draemon
+1  A: 

Since I didn't need to select rows, I ended up just dynamically adding and elements to a JPanel with a custom layout. Allowed for full component behaviour without having to hack a table.

Allain Lalonde