Java / Swing - 将组件添加到JList

问题描述 投票:0回答:2

我有一个JList,我需要添加组件。我所做的是我创建了一个DefaultListModel,它采用了我所创建的Component的类型。我的代码将它添加到DefaultListModel,它确实显示信息,但它只是String格式的组件名称。我该如何让它实际显示组件而不是组件的名称?它甚至可能吗?

这是我的代码

    DefaultListModel<CustomComponent> jListModel = new DefaultListModel<>();
jListModel.addElement(new CustomComponent()); //Adds the name of the component(not what I want)
java swing components add jlist
2个回答
1
投票

在方法中实现ListCellRenderer类

Component getListCellRendererComponent(
    JList<? extends E> list,
    E value,
    int index,
    boolean isSelected,
    boolean cellHasFocus);

所有你需要的是返回value。在您的情况下,值是list元素,它是Custom Component实例。最简单的方法。

但这不是正确的做法。列表模型应该保留数据(而不是组件)。而是为渲染器定义一个CustomComponent实例,并在getListCellRendererComponent()中调用customComponentInstance.init(value)之类的东西,让CustomComponent反映模型中的数据。


0
投票

有可能的。您需要编写自己的ListCellRenderer,它返回您的Component,而不是默认的JLabel。

例:

public class ComponentListCellRenderer {

    public ComponentListCellRenderer() {
    }

    public Component getListCellRendererComponent(JList<?> list, Object value, int            index, boolean isSelected, boolean cellHasFocus) {
    Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        if (value instanceof Component){
            c = (Component) value;
            c.setPreferredSize(c.getSize());
        }

        return c;
    }

}

在这种情况下,默认的Component c被拦截并与您自己的组件交换,这将是value。我们需要将Component的preferred size设置为它的大小,否则JList不会正确显示Component。

如何使用:

  • 创建一个新的JList<CustomComponent>()
  • 将它的ListCellRenderer设置为新的ComponentListCellRenderer
© www.soinside.com 2019 - 2024. All rights reserved.