Why I can't add a JLabel object into JList/JComboBox?

R

RC

I'm try to make a list with different background colors.

Here is what I do


JLabel label1 = new JLabel("Red Background");
JLabel label2 = new JLabel("Blue Background");
label1.setBackground(Color.red);
label2.setBackground(Color.blue);

Dimension d = new Dimension(80, 20);
label1.setPreferredSize(d);
label1.setMaximumSize(d);
label1.setMinimumSize(d);
label2.setPreferredSize(d);
label2.setMaximumSize(d);
label2.setMinimumSize(d);

DefaultListModel listModel = new DefaultListModel();
JList list = new JList(listModel);

listModel.addElement(label1);
listModel.addElement(label2);
list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
list.setVisibleRowCount(4);
list.setLayoutOrientation(JList.VERTICAL);
list.setDragEnabled(true);

JScrollPane scrollPane = new JScrollPane(list);

There are no compiling error messages.
But here is the run-time error adding to the JList instead
the JLabels

javax.swing.JLabel[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.0,border=,flags=8388608,maximumSize=java.awt.Dimension[width=.....]

Can anyone tell me how to achieve my goal, have different background
colors in a list?

Thank Q very much in advance!
 
V

VisionSet

Can anyone tell me how to achieve my goal, have different background
colors in a list?

You can't add Components directly because swing optimises the drawing
process by using one component to render all elements. ie as it iterates
through the elements in order to draw it take a single component and changes
its state then draws it to the graphics object.
So you need a different approach that uses swings optimised mechanism.

see
http://java.sun.com/docs/books/tutorial/uiswing/components/list.html#renderer

All list/table type components work the same way, so other tutorials will be
just as good to get the gist.

http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html#renderer
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,733
Messages
2,569,439
Members
44,829
Latest member
PIXThurman

Latest Threads

Top