> I am trying to get a JList to display each item as a JPanel consisting of
> three JLabels arranged in a GridLayout of 1 row and 3 columns. I have
[quoted text clipped - 8 lines]
> how to render the class given that it is a JPanel. Are there any other
> steps that I may be missing?
Hmm, I can get a custom list (a different one) to work if I use JLabel as
the base type for my CustomListCell but not when I use JPanel. The list
entry is being displayed (ie. I can select it) but there is nothing in it.
Which begs me to ask, can I use a JPanel to display items in a JList? Maybe
there is a restriction I am unaware of. In my CustomListCellRenderer I
explicitly set the text of all 3 JLabels but they are displaying as blank.
Thanks,
Wes
Michael Dunn - 04 Nov 2005 19:37 GMT
>> I am trying to get a JList to display each item as a JPanel consisting of
>> three JLabels arranged in a GridLayout of 1 row and 3 columns. I have
[quoted text clipped - 21 lines]
> there is a restriction I am unaware of. In my CustomListCellRenderer I
> explicitly set the text of all 3 JLabels but they are displaying as blank.
works OK like this
import javax.swing.*;
import java.awt.*;
class Testing extends JFrame
{
DefaultListModel dlm = new DefaultListModel();
JList list = new JList(dlm);
public Testing()
{
setLocation(400,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
list.setCellRenderer(new MyRenderer());
JScrollPane sp = new JScrollPane(list);
sp.setPreferredSize(new Dimension(100,200));
getContentPane().add(sp);
pack();
for(int x = 1; x < 100; x += 3) dlm.addElement(new
String[]{""+x,""+(x+1),""+(x+2)});
}
public static void main(String[] args){new Testing().setVisible(true);}
}
class MyRenderer extends JPanel implements ListCellRenderer
{
JLabel[] lbl = new JLabel[3];
public MyRenderer()
{
setLayout(new GridLayout(0,3));
for(int x = 0; x < lbl.length; x++)
{
lbl[x] = new JLabel();
lbl[x].setOpaque(true);
add(lbl[x]);
}
}
public Component getListCellRendererComponent(JList list,Object value,
int index,boolean isSelected,boolean cellHasFocus)
{
for(int x = 0; x < lbl.length; x++)
{
lbl[x].setText((String)((String[])value)[x]);
if(cellHasFocus) lbl[x].setBackground(Color.CYAN);
else lbl[x].setBackground(Color.WHITE);
}
return this;
}
}