0

为了在 JList 中的项目旁边获得图标,我按照教程创建了一个基本类来存储我的 JList 项目。然后我使用这个类作为我的列表模型来打印出每个项目的图标和文本。

我还使用 getListCellRendererComponent 来打印文本和图标。

我的 ListItem 类如下所示:

public class ListItem 
{
    private ImageIcon icon = null;
    private String text;

    public ListItem(String iconpath, String text) 
    {
        icon = new javax.swing.ImageIcon(getClass().getResource(iconpath));

        this.text = text;
    }       

    public ImageIcon getIcon() 
    {
        return icon;
    }

    public String getText() 
    {
        return text;
    }
}

MyCellRenderer:

public class MyCellRenderer
extends JPanel
implements ListCellRenderer
{
    private JLabel label = null;

    public MyCellRenderer()
    {
        super(new FlowLayout(FlowLayout.LEFT));

           setOpaque(true);


        label = new JLabel();
        label.setOpaque(false);

        add(label);                
    }


    public Component getListCellRendererComponent(JList list, 
                                                  Object value, 
                                                  int index,    
                                                  boolean iss,  
                                                  boolean chf)  
    {


        label.setIcon(((ListItem)value).getIcon());

        label.setText(((ListItem)value).getText());

        if(iss) setBackground(Color.lightGray); 
        else setBackground(list.getBackground()); 

        return this;
    }
}

最后,这就是我创建列表的方式:

listmodel = new DefaultListModel();

ListItem item0 = new ListItem("/resources/icnNew.png", "Element 1"),
         item1 = new ListItem("/resources/icnNew.png", "Element 2");

listmodel.addElement(item0);  
listmodel.addElement(item1);


list = new JList(listmodel);

list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setLayoutOrientation(JList.VERTICAL);

list.setFixedCellHeight(32);        

list.setCellRenderer(new MyCellRenderer());

menuScrollPane = new JScrollPane(list);

pnlVisitorsList.add(menuScrollPane, BorderLayout.CENTER);

我如何遍历整个列表并获取元素名称?

例如元素 1、元素 2

我想查看所有项目并更改名称和图标..

4

1 回答 1

1
// LOOP

// loop through all elements in the list
for (int i=0; i<listmodel.size(); i++) {

    // get the listitem associated with the current element
    final Object object = listmodel.get(i);
    if (object instanceof ListItem) {
        ListItem listitem = (ListItem) object;

        // use getText() to get the text asociated with the listitem
        System.out.print(listitem.getText());

        // test if the current item is selected or not
        if (list.isSelectedIndex(i)) {
            System.out.print(" (selected)");
        }

        // next
        System.out.println();
    }
}

// CHANGE NAME + ICON

// create a new list item
ListItem itemNew = new ListItem("/resources/icnNew.png", "Element 3");

// replaced the first item in the list with the new one
listmodel.set(0, itemNew);
于 2013-07-23T16:54:34.807 回答