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!
VisionSet - 22 Feb 2006 12:31 GMT
> 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
--
Mike W
Paul Hamaker - 22 Feb 2006 13:33 GMT
http://forum.java.sun.com/thread.jspa?threadID=602806&messageID=3270525
John O'Conner - 23 Feb 2006 16:21 GMT
> Can anyone tell me how to achieve my goal, have different background
> colors in a list?
The following article uses an example that displays colors in a JList. I
think you should be able to pick up the sample code to solve your
problem. Don't forget to leave a comment if the article helps.
http://java.sun.com/developer/technicalArticles/GUI/jlist/
Regards,
John O'Conner