JList找出点击的项目

时间:2013-07-23 16:19:57

标签: java swing jlist

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

我还使用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

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

1 个答案:

答案 0 :(得分: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);