Retrieving specific item from a JList

606 Views Asked by At

I have a list of JXHyperlinks, I need to retrieve them one by one and add to a panel

the code is:

for(int i=1; i<=lcol-1;i++)
{
    a2=sheet.getCell(i,0);
    stringy=a2.getContents();
    testlink= new JXHyperlink(new Action(stringy));
    list.add(testlink);

}
for(int i=0;i<list.getModel().getSize();i++)
{
    panel2.add(list.getModel().getElementAt(i));

}

the first loop is creating the list of links with their respective names (taken from an excel file). The second loop takes the pre-made list and adds each object to a panel. The problem is that id doesn't add them.

2

There are 2 best solutions below

0
On

The problem is, you are adding the JXHyperlink components directly to the list, not the list model.

for(int i=1; i<=lcol-1;i++)
{
    a2=sheet.getCell(i,0);
    stringy=a2.getContents();
    testlink= new JXHyperlink(new Action(stringy));
    // I'm the JList, not it's model :P
    list.add(testlink);
}
// I bet nothing exists in the model
for(int i=0;i<list.getModel().getSize();i++)
{
    panel2.add(list.getModel().getElementAt(i));
}

This is not how lists should work.

Instead, add the link String to the ListModel and use the JXHyperlink as a bases for a ListCellRenderer, then add an instance of JXHyperlink to the panel for each String in the list

See How to use lists for more details, in particular, Creating a model and Writing a Custom cell Renderer

0
On

You are confusing List with JList. List#add is inhered from Collection, and adds a Object to itself. JList#add is inhered from Container and adds a component to a Container. So Jlist#add its like JPanel#add