expanding JList item
Hi
I am currently using a custom ListCellRenderer for my listitems that return a JLabel with a icon and some text. What I want is for the item to expand with a new line of text when selected.
I tried returning a JPanel instead, but that only led to complications with height/width of the item(s). Any ideas? Want something like the windows control panel add&remove programs list.
[402 byte] By [
invictus2a] at [2007-10-2 10:24:45]

[nobr]this works OK on 1.4.0_01
(I didn't worry about the icon bit)
click any item in the list - the first time there is a slight delay due to the html
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
class Testing extends JFrame
{
String[] cities = {"London","Madrid","New York","Rome","Sydney","Toronto","Washington"};
DefaultListModel listModel = new DefaultListModel();
JList list = new JList(listModel);
int currentSelection = -1;
public Testing()
{
setLocation(400,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
list.setCellRenderer(new MyRenderer());
for(int x = 0; x < cities.length; x++) listModel.addElement(cities[x]);
JScrollPane sp = new JScrollPane(list);
sp.setPreferredSize(new Dimension(100,150));
getContentPane().add(sp);
pack();
list.addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent lse){
if(lse.getValueIsAdjusting() == false)
{
for(int x = 0; x < listModel.size(); x++)
{
listModel.setElementAt(listModel.getElementAt(x),x);
}
}}});
}
class MyRenderer extends DefaultListCellRenderer
{
public Component getListCellRendererComponent(JList list,Object value,
int index,boolean isSelected,boolean cellHasFocus)
{
JLabel lbl = (JLabel)super.getListCellRendererComponent(list,value,index,isSelected,cellHasFocus);
if(list.getSelectedIndex() == index) lbl.setText("<html>"+value+"<br>another line of text</html>");
else lbl.setText(""+value);
return lbl;
}
}
public static void main(String[] args){new Testing().setVisible(true);}
}
[/nobr]