0

以下 ListCellRenderer 不接收嵌套 ComboBox 上的单击事件。我需要启用某些东西吗?

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;
    }

}
4

3 回答 3

1

swing 中的渲染器组件就像“橡皮图章”一样工作——它们只是用于渲染/绘制一个值,而不是以通常的方式添加到父容器中(想想如何在多个地方添加单个组件!)。

听起来您可能想要一个编辑器而不是渲染器(编辑器是一个成熟的组件,在任何给定时间添加到一个地方)。如果失败,您将不得不在 JList 上安装 MouseListener。

于 2008-10-09T20:13:27.767 回答
1

因为我不需要选择行,所以我最终只是动态地将元素添加到具有自定义布局的 JPanel 中。允许完整的组件行为,而无需破解表。

于 2008-10-11T00:06:32.573 回答
0

这有点棘手。我相信您需要用单列 JTable 替换 JList。然后设置一个表格单元格编辑器以及渲染器。IIRC,丢失第一次单击(用于选择已编辑的单元格)可能会出现问题。

此外,在每次调用 getCellRendererComponent 之间重用组件也是一个好主意。这些组件被用作印章,然后被丢弃。如果每次都重新创建它们,性能将非常糟糕。

于 2008-10-09T18:27:55.123 回答