简体   繁体   English

将图像添加到 JList 项

[英]Add an image to a JList item

I have a JList and i am using DefaultListModel,everything is well and the items(strings)are added correctly, but i want to add an image in JList beside each string (egto show the status of the users).Can anyone help me about that?我有一个 JList 并且我正在使用 DefaultListModel,一切都很好并且项目(字符串)被正确添加,但我想在每个字符串旁边的 JList 中添加一个图像(例如显示用户的状态)。任何人都可以帮助我那? Thanks in advance.Here is how i add the elements,can i add images too?在此先感谢。这是我添加元素的方法,我也可以添加图像吗?

private  DefaultListModel modelO = (DefaultListModel) Teacher.made_list.getModel();
((DefaultListModel) Teacher.made_list.getModel()).addElement(studName);

You have to implement ListCellRenderer (or extend DefaultListCellRenderer ) and have the getListCellRendererComponent method to return a Jlabel with an icon in it.您必须实现ListCellRenderer (或扩展DefaultListCellRenderer )并使用getListCellRendererComponent方法返回一个带有图标的Jlabel

Example:例子:

public class IconListRenderer extends DefaultListCellRenderer {
    public Component getListCellRendererComponent(
            JList list, Object value, int index,
            boolean isSelected, boolean cellHasFocus) {
        JLabel label = (JLabel) super.getListCellRendererComponent(
                list, value, index, isSelected, cellHasFocus);
        Icon icon = this.getIcon(list, value, index, isSelected, cellHasFocus)
        label.setIcon(icon);
        return label;
    }
    protected Icon getIcon(
            JList list, Object value, int index,
            boolean isSelected, boolean cellHasFocus) {
        // how do I get icon?
    }
}

You have to implement the getIcon method.您必须实现getIcon方法。

The model is used to store the data, and a renderer is used to display the data. model用于存储数据,渲染器用于显示数据。 The default renderer can handle Strings and icons but if you need to do more than that, you can provide a custom renderer.默认渲染器可以处理字符串和图标,但如果您需要做更多的事情,您可以提供自定义渲染器。 Here is an example .这是一个例子 It's for a combo box, but the renderer is the same for JLists.它用于组合框,但 JLists 的渲染器是相同的。

Here you can find complex solution including在这里您可以找到复杂的解决方案,包括

  • Custom JList elements (that allows to get icon image from list element)自定义 JList 元素(允许从列表元素中获取图标图像)
  • Handling selection styling处理选择样式
  • More convinient way of using ListCellRenderer than just extending Default使用 ListCellRenderer 比仅仅扩展 Default 更方便的方式

http://www.codejava.net/java-se/swing/jlist-custom-renderer-example http://www.codejava.net/java-se/swing/jlist-custom-renderer-example

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM