【问题标题】:Java/Swing - Add a Component to a JListJava/Swing - 将组件添加到 JList
【发布时间】:2015-10-30 21:27:44
【问题描述】:

我有一个需要添加组件的 JList。我所做的是我制作了一个 DefaultListModel,它采用了我制作的 Component 的类型。我的代码将它添加到 DefaultListModel,它确实显示信息,但它只是字符串格式的组件名称。我应该如何让它实际显示组件而不是组件的名称?有没有可能?

这是我的代码

    DefaultListModel<CustomComponent> jListModel = new DefaultListModel<>();
jListModel.addElement(new CustomComponent()); //Adds the name of the component(not what I want)

【问题讨论】:

  • “组件”是指 Swing 组件?能给我举个例子吗?还有你所说的“字符串格式”是什么意思?
  • 您是否尝试在 CustomComponent 中覆盖 toString()
  • 即使你可以显示组件它也不会工作。它只是组件的绘制,而不是用户可以与之交互的真实组件。

标签: java swing components add jlist


【解决方案1】:

实现您的 ListCellRenderer 类 在方法中

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

您只需返回value。在您的情况下,该值是列表元素,它是 CustomComponent 实例。这是最简单的方法。

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

【讨论】:

    【解决方案2】:

    这是可能的。 您需要编写自己的 ListCellRenderer,它会返回您的组件,而不是默认的 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。 我们需要将组件的preferred size 设置为它的大小,否则 JList 将无法正确显示组件。

    使用方法:

    • 创建一个新的JList&lt;CustomComponent&gt;()
    • ListCellRenderer 设置为新的 ComponentListCellRenderer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-09
      • 1970-01-01
      • 1970-01-01
      • 2011-09-24
      • 1970-01-01
      • 2014-06-05
      相关资源
      最近更新 更多