Adding JLabels to a JList?

Go To StackoverFlow.com

2

So far, I've tried simply going through my labels and adding each one to the list's list model with:

listModel.addElement(label);

So this works, but it simply gives a string representation of the label rather than the actual label.

Basically, is it possible to have a JList of JLabels? If not, then what's a good way to have a scrollable list of JLabels that I can update?

2012-04-05 17:27
by idolos
Looks like there is something fundamentally wrong in what you are trying to do. The JList already presents you like a list of labels ( non editable items that you can change via code). You may want to update your question with more detail. And, the DefaultListCellRenderer already extends JLabe - ring bearer 2012-04-05 17:38
Ah, I see what you mean. I'm trying to do something like this, though, and it seemed like it would be appropriate to use JLabels - idolos 2012-04-05 17:45
may be just use HTML in your label - tenorsax 2012-04-05 17:48
Yeah, that's what I currently have. I'm able to generate the labels fine, but I'm not really sure where to put them afterwards to achieve the desired effect. A JList seemed appropriate in thought, but it doesn't seem to work well in practice - idolos 2012-04-05 17:49


1

JList, JTable, JComboBox's popup return by default JLabel / JComponent from the Renderer, then there is no reason to put those JComponents types to the JList (in this case)

but it simply gives a string representation of the label rather than the actual label
  • please read how Renderer to works, JLabel and Icon, examples here and here,

  • concept of Renderers is similair for JList, JTable, JComboBox's popup

2012-04-05 17:41
by mKorbel
So in that case, where would it be appropriate to put JLabels if I wished to scroll through them and be able to select one? A JScrollPane - idolos 2012-04-05 17:50
right, hmmm this one could be interesting, please read this threadmKorbel 2012-04-05 17:57
That looks like what I want, thank you - idolos 2012-04-05 18:01


1

There is (almost) never a need to put a JComponent in the model side of a Swing component (JList, JTree, JTable, ... ). In your ListModel you put the Objects you want to visualize in a JList, and you let the renderer take care of the representation.

So if you want to represent each Object as a special label you create that label in your renderer.

See the Swing list tutorial for more information. This tutorial does not contain a custom renderer, but instead refers you to the custom renderer section of the combobox tutorial, which is very similar

2012-04-05 17:55
by Robin
I'll take a look at that, thanks - idolos 2012-04-05 18:00
Ads