JList as a custom JTable CellRenderer

Hi,

I wrote a custom Cell Renderer for JTable:

public class ListRenderer extends JList implements TableCellRenderer

{

public DefaultListModel listModel = new DefaultListModel();

public MyListRenderer myListRenderer;

ImageIcon icon=null;

public ListRenderer(ImageIcon icon)

{

this.icon=icon;

try {

jbInit();

}

catch(Exception e) {

e.printStackTrace();

}

}

public Component getTableCellRendererComponent(JTable table, Object value,

boolean isSelected, boolean hasFocus, int row, int column)

{

return this;

}

private void jbInit() throws Exception

{

this.setModel ( listModel ) ;

this.addMouseListener(new ListRenderer_this_mouseAdapter(this));

myListRenderer = new MyListRenderer(icon);

this.setCellRenderer ( myListRenderer ) ;

}

void this_mouseReleased(MouseEvent e)

{

}

}

class ListRenderer_this_mouseAdapter extends java.awt.event.MouseAdapter {

ListRenderer adaptee;

ListRenderer_this_mouseAdapter(ListRenderer adaptee) {

this.adaptee = adaptee;

}

public void mouseReleased(MouseEvent e) {

adaptee.this_mouseReleased(e);

}

}

The JList has a Cell Renderer itself:

public class MyListRenderer extends DefaultListCellRenderer

{

ImageIcon icon;

public MyListRenderer(ImageIcon icon)

{

this.icon=icon;

}

public Component getListCellRendererComponent(JList list,

Object value,

int index,

boolean isSelected,

boolean hasFocus)

{

JLabel label =(JLabel)super.getListCellRendererComponent(list,value,

index,

isSelected,

hasFocus);

label.setIcon(icon);

return (label);

}

}

I set one of the colums with the custom renderer:

list = new ListRenderer(icon);

getColumn("Event").setCellRenderer(list);

No I tried adding items to the list:

list.listModel.addElement("Any");

list.listModel.addElement("thing");

It works fine except one problem, It adds elements to all my rows in the table instead of just adding to the selected row.

Any idea on how to solve this?

[2292 byte] By [Gilco] at [2007-9-30 21:34:15]
# 1

Hello,

First you have to understand that you only have one instance of your ListRenderer for a given column. Since you return this in getTableCellRendererComponent, the same list is used to render all rows of the table.

What you need to do is somehow set the model of your list according to the row selected.

weebib at 2007-7-7 3:05:29 > top of Java-index,Desktop,Core GUI APIs...