Changing JList cell renderer on selection

Hi,
In our application we need to change the renderer of the selected cell of JList to JTextArea while maintaining default cell renderer for unselected cells. I tried by providing custom cell renderer (code is given below) but it does not work..:-(. Though the component used by JList for rendering the cell is JTextArea, the height of the cell remains same as that of unselected cells. Our requirement is to change the cell height of the selected row so as to give a feel that selected row expands and shows some more information about the selected item to the user.
Here is the code snippet of the cell renderer that I wrote:
class CellRenderer1 extends DefaultListCellRenderer{
private JTextArea selTxtArea;
CellRenderer1() {
selTxtArea = new JTextArea(3,20);
this.setOpaque(true);
public Component getListCellRendererComponent(JList list,
Object value, int index,
boolean isSelected, boolean cellHasFocus) {
String name = (String) value;
if ( isSelected ) {
selTxtArea.setBackground(list.getSelectionBackground());
selTxtArea.setForeground(list.getSelectionForeground());
selTxtArea.setText(name + "\n" + name);
return selTxtArea;
else {
this.setBackground(list.getBackground());
this.setForeground(list.getForeground());
this.setText(name);
return this;
//return this;
Any pointers or help will be highly appreciated.
Thanks
Atul

JList calculates fixedCellHeight and then uses the same for every cell. This was causing the problem. By overriding the getRowHeight method of BasicListUI class I was able to achieve different cell heights for selected and unselected rows. Following is the code snippet which shows how this was achieved:
protected int getRowHeight(int row) {
if ( (cellHeights == null) || (cellHeights.length < row )) {
cellHeights = new int[row];
ListModel model = list.getModel();
Object value = model.getElementAt(row);
ListSelectionModel selModel = list.getSelectionModel();
boolean isSelected = selModel.isSelectedIndex(row);
Component comp = list.getCellRenderer().
getListCellRendererComponent( list, value, row,
isSelected, false);
Dimension dim = comp.getPreferredSize();
int height = dim.height;
cellHeights[row] = height;
return cellHeights[row];
}

Similar Messages

  • Customizing JList Cell Renderer

    Hi all,
    I got a problem with JList not rendering properly in my program. basically I create a customized renderer by extending JPanel and implementing ListCellRenderer.
    but somehow i cannot get the tooltiptext from the JLabel inside my JPanel (the renderer) to display the tooltiptext and responding to my mouse gesture. here's a snippet of my code.
    did i do something wrong?
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class TestR {
         private static class ListItem {
              private Color color;
              private String value;
              public ListItem(Color c, String s) {
                   color = c;
                   value = s;
              public Color getColor() {
                   return color;
              public String getValue() {
                   return value;
         private static class MyCellRenderer extends JPanel implements
                   ListCellRenderer {
              private JLabel lbl;
              public MyCellRenderer() {
                   // Don't paint behind the component
                   setOpaque(true);
                   setLayout(new BorderLayout());
                   lbl = new JLabel();
                   add(lbl);
              // Set the attributes of the
              //class and return a reference
              public Component getListCellRendererComponent(JList list, Object value, // value to display
                        int index, // cell index
                        boolean iss, // is selected
                        boolean chf) // cell has focus?
                   // Set the text and
                   //background color for rendering
                   lbl.setText(((ListItem) value).getValue());
                   lbl.setToolTipText("tooltip: "+((ListItem) value).getValue());
                   setBackground(((ListItem) value).getColor());
                   // Set a border if the
                   //list item is selected
                   if (iss) {
                        setBorder(BorderFactory.createLineBorder(Color.blue, 2));
                   } else {
                        setBorder(BorderFactory.createLineBorder(list.getBackground(),
                                  2));
                   return this;
         // Create a window
         public static void main(String args[]) {
              JFrame frame = new JFrame("Custom List Demo");
              frame.addWindowListener(new WindowAdapter() {
                   @Override
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              // Use a list model that
              //allows for updates
              DefaultListModel model = new DefaultListModel();
              JList statusList = new JList(model);
              statusList.setCellRenderer(new MyCellRenderer());
              // Create some dummy list items.
              ListItem li = new ListItem(Color.cyan, "test line one");
              model.addElement(li);
              li = new ListItem(Color.yellow, "foo foo foo");
              model.addElement(li);
              li = new ListItem(Color.green, "quick brown fox");
              model.addElement(li);
              // Display the list   
              JPanel panel = new JPanel();
              panel.add(statusList);
              frame.getContentPane().add("Center", panel);
              frame.pack();
              frame.setVisible(true);
    }

    hi!
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class TestR {
         private static class ListItem {
              private Color color;
              private String value;
              public ListItem(Color c, String s) {
                   color = c;
                   value = s;
              public Color getColor() {
                   return color;
              public String getValue() {
                   return value;
         private static class MyCellRenderer extends JPanel implements
                   ListCellRenderer {
              private JLabel lbl;
              public MyCellRenderer() {
                   // Don't paint behind the component
                   setOpaque(true);
                   setLayout(new BorderLayout());
                   lbl = new JLabel();
                   add(lbl);
              // Set the attributes of the
              //class and return a reference
              public Component getListCellRendererComponent(JList list, Object value, // value to display
                        int index, // cell index
                        boolean iss, // is selected
                        boolean chf) // cell has focus?
                   // Set the text and
                   //background color for rendering
                   lbl.setText(((ListItem) value).getValue());
                   /*lbl.*/setToolTipText("tooltip: "+((ListItem) value).getValue());
                   setBackground(((ListItem) value).getColor());
                   // Set a border if the
                   //list item is selected
                   if (iss) {
                        setBorder(BorderFactory.createLineBorder(Color.blue, 2));
                   } else {
                        setBorder(BorderFactory.createLineBorder(list.getBackground(),
                                  2));
                   return this;
         // Create a window
         public static void main(String args[]) {
              JFrame frame = new JFrame("Custom List Demo");
              frame.addWindowListener(new WindowAdapter() {
                   @Override
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              // Use a list model that
              //allows for updates
              DefaultListModel model = new DefaultListModel();
              JList statusList = new JList(model);
              statusList.setCellRenderer(new MyCellRenderer());
              // Create some dummy list items.
              ListItem li = new ListItem(Color.cyan, "test line one");
              model.addElement(li);
              li = new ListItem(Color.yellow, "foo foo foo");
              model.addElement(li);
              li = new ListItem(Color.green, "quick brown fox");
              model.addElement(li);
              // Display the list   
              JPanel panel = new JPanel();
              panel.add(statusList);
              frame.getContentPane().add("Center", panel);
              frame.pack();
              frame.setVisible(true);
    }try this out. this may help you. note at line no 50. /*lbl.*/setToolTipText("tooltip: "+((ListItem) value).getValue());:)
    Aniruddha

  • Best Practice for Changing the Cell-Renderer in a TreeTab

    I've implemented a TreeTable (sap.ui.table.TreeTable). Now, I would like to change the way how table cells are being rendered. Intuitively, I would create a subclass "myrenderer" which extends sap.ui.table.TableRenderer.renderTableCell and assign this renderer as cell renderer with something like (pseudocode):
    myTreeTable.setCellRenderer(myrenderer);
    Any help/hint would be appreciated. An example would be appreciated even more ;-).
    Bye
        Christian

    Hi Christian
    You can extend from sap.ui.table.TreeTable like this Example
    -D

  • Custom JList Cell renderer

    Hey guys, i've made a JList put it inside a JScrollPane.
    All working nicely.
    I'm making my own cell renderer, which extends JLabel and implements ListCellRenderer, just the usual
    inside the getList...Component() method, im just adding in a new Icon and adding a border
    And setting the text via the setText method, also using a bit of html to format the text so it sits there nicely.
    It's exactly how i want it, however there's this issue, when i populate alot of items for some reason the JScrollPane isnt like aware of more items and scroll bar isnt made, but u can tell theres more because its cut off at the end.
    Also, when i resize it so the JScrollPanes width is really small, each JList items text is wrapped and causing some of the text to be hidden.
    I want to know how to fix these issues with no horizontal scroll bar etc
    what exactly is the issue?
    Is it because of the custom renderer?
    Thanks for your help guys.

    Is it because of the custom renderer?You tell us!
    Somewhere in your code you have the line:
    list.setCellRenderer(...);
    If you comment out that line does it work correctly? If so then the problem is the renderer and we can't help you solve the problem since we don't know what your code looks like.
    If you need furthre help then you need to post a [url http://www.physci.org/codes/sscce.jsp]Simple Executable Demo Program that shows the problem

  • Using jtextpane as jlist cell renderer component

    hi,
    I want to use Jlist (in a Jscrollpane) to list a series of boxes of text. The boxes have to be kept the same width, but the height can vary depending on the amount of text.
    I want to use jtextpane because it wraps automatically on word boundaries... although I am confused by the jtextpane functionality...
    but I just can't seem to crack it: presumably its going to involve
    class MyCellRenderer extends JTextPane implements CellRenderer {
    public Component getListCellRendererComponent( ...
    then what ??? help!
    mike rodent
    PS also, how to make Jlist put a line (a single line) between each of the components in its list... it's no good doing setBorder inside the above method, as you then get 2 lines coalescing between adjacent Jlist elements...

    PS also, how to make Jlist put a line (a single line) between each of
    the components in its list... it's no good doing setBorder inside the
    above method, as you then get 2 lines coalescing between adjacent
    Jlist elements...Who says you need to have a Border with top and bottom lines?

  • Custom Cell Renderer for JList

    I'm getting some strange behaviour from my custom cell renderer.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class TestRenderer implements ListCellRenderer {
      private JPanel jpCell = new JPanel();
      public Component getListCellRendererComponent
          (JList list, Object value, int index, boolean isSelected,
           boolean cellHasFocus) {
        jpCell.add(new JLabel("Render"));
        return jpCell;
    import javax.swing.*;
    import java.awt.*;
    public class TestPanel extends JFrame {
         public TestPanel() {
              JList jlst = new JList(new String[]{"Value", "Value2", "Value3"});
              jlst.setCellRenderer(new TestRenderer());
              JPanel panel = new JPanel();
              panel.add(jlst);
              add(panel);
         public static void main(String[] args) {
              TestPanel frame = new TestPanel();
              frame.setSize(300, 300);
              frame.setLocationRelativeTo(null);
              frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
              frame.setVisible(true);
    }As you will see the renderer displays the string several times in each cell depending on which layout manager I use. However, if I replace the JPanel with a JLabel and set the String as text on the label the String is only printed once per cell. I can't see to find the reason for this.
    Edited by: 811488 on 18-Nov-2010 09:44
    Edited by: 811488 on 18-Nov-2010 09:45
    Edited by: 811488 on 18-Nov-2010 09:45

    So getListCellRendererComponent returns a component whose paintComponent method is called with the Graphics object of the JList Yes, except that the paint(...) method is called. There is a difference. paintComponent() only paints the component. In the case of a JPanel you would get a boring gray colored component. paint() will paint the component and its children and the Border of the component as well. So you get a much more exiting component.
    Read the section from the Swng tutorial on [url http://download.oracle.com/javase/tutorial/uiswing/painting/index.html]Custom Painting for more information.
    So the state of the cell is not the state of the cell Renderer Component meaning the image rendered onto the cell only reflects the state of the Cell Renderer Component at the time the cell was rendered.Yes which is why this method should be efficient because repainting is consistently being done for all the cells. For example every time row selection changes multiple rows need to be repainted. Think of this same concept when you use a JTable which also contains multiple columns for each row.
    That is why you should not be adding/removing components in the rendering code.
    It makes sense except that if this was the case the first version of the Render that I posted should have been rendered first with one "Render" then two then three, shouldn't it?Yes, except that you can't control when or how often the rendering is done. Add the following to the renderer:
    System.out.println(index + " : " + jpCell.getComponentCount());You will see that rendering is done multiple times. The JList tries to determine its preferred width. To do this it loops through all the items in the list and invokes the renderer to get the width of the largest renderer. Well the largest width is the last renderer because 3 labels have been added to the panel. So that width becomes the preferred width of the list. Then the GUI is displayed and the list is painted. Every time the renderer is called an new label is added, but after the 3rd label there is no room to paint the label so it is truncated.
    Change your code to the following:
    //add(panel);
    add(jlst);Now change the width of the frame to see what happens.
    Given all the help you have received, I expect to see many "helpfull answers" selected as well as a "correct answer" (if you want help in the future that is).

  • Changing JList non-editable Font color of the selected items

    Hi All,
    I want to change the font color of non-editable JList's selected items which is not clearly visible to user. And I need to change the font color only the selected item in this scenerio.
    Could you please clarify me?
    <img src="file:///C:/DOCUME~1/sgnanasi/LOCALS~1/Temp/moz-screenshot-4.png" alt="" />

    [email protected] wrote:
    ..I want to change the font color of non-editable JList's selected items which is not clearly visible to user. And I need to change the font color only the selected item in this scenerio.Set a custom [cell renderer|http://java.sun.com/javase/6/docs/api/javax/swing/ListCellRenderer.html] *(<- link)* for the JList.

  • Jlist as a Cell Renderer

    Hi ,
    I would reaally appreciate if someone could post an example of using a JList as a custom Cell renderer
    Thank you.

    Here's a start (I couldn't be bothered to set an editor too):import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class Test extends JFrame {
        public Test () {
            JTable table = new JTable (new TestTableModel ());
            table.setDefaultRenderer (Integer[].class, new TestTableCellRenderer ());
            table.setRowHeight (50);
            getContentPane ().setLayout (new BorderLayout ());
            getContentPane ().add (new JScrollPane (table));
            setDefaultCloseOperation (DISPOSE_ON_CLOSE);
            setTitle ("Test");
            pack ();
            setLocationRelativeTo (null);
            setVisible (true);
        public static void main (String[] parameters) {
            new Test ();
        private class TestTableModel implements TableModel {
            private final static int N = 10;
            private Object[][] data;
            private ColumnData[] columnData;
            public TestTableModel () {
                data = new Object[N][2];
                for (int i = 0; i < N; i ++) {
                    data[0] = new Integer (i);
    data[i][1] = new Integer[i + 1];
    for (int j = 0; j <= i; j ++) {
    ((Integer[]) data[i][1])[j] = new Integer (j);
    columnData = new ColumnData[] {
    new ColumnData ("n", Integer.class),
    new ColumnData ("0..n", Integer[].class)
    public int getColumnCount () {
    return columnData.length;
    public int getRowCount () {
    return data.length;
    public boolean isCellEditable (int row, int column) {
    return false;
    public void setValueAt (Object value, int row, int column) {}
    public Class getColumnClass (int column) {
    return columnData[column].classType;
    public Object getValueAt (int row, int column) {
    return data[row][column];
    public String getColumnName (int column) {
    return columnData[column].name;
    public void addTableModelListener (TableModelListener listener) {}
    public void removeTableModelListener(TableModelListener listener) {}
    private class ColumnData {
    public String name;
    public Class classType;
    public ColumnData (String name, Class classType) {
    this.name = name;
    this.classType = classType;
    private class TestTableCellRenderer extends JScrollPane implements TableCellRenderer {
    private JList list;
    public TestTableCellRenderer () {
    list = new JList ();
    setViewportView (list);
    public Component getTableCellRendererComponent (JTable table, Object value, boolean selected, boolean focused, int row, int column) {
    list.setListData ((Integer[]) value);
    return this;
    Kind regards,
      Levi

  • How do I change the colour of a selected cell in a jTable?

    I have a Jtable that displays URL names in one column. There are several problems I'm having. The effect I'm trying to achieve is this:
    When the user runs the mouse over the URL name the cursor should change into a hand (similar to what happens in an HTML hyperlink). I'm aware that the Cursor class can set the cursor graphic so i figure that i need a listener of some sort on each cell (so the cursor can change from an arrow to a hand) and also one to indicate when the cursor is not on a cell (so that it can change from a hand back into an arrow). Is this the right track?
    Also, I've looked at the DefaultTableCellRenderer class (which, as i understand it, is responsible for how each cell in the jtable is displayed) for a method that will allow me to set the background of a selected cell (or row or column). I require this because each time i select a cell (or row) it becomes highlighted in blue. I would rather it just remained white and changed the cursor to a hand. I know there exists a method for setting the background for an unselected cell but none for a selected cell. Again, I'm not sure if I'm going down the right track with this approach.
    Lastly, if the cell has been selected (by a mouse click) the font of the writing in the cell (i.e. The name of the URL) should change. This shouldn't be too much of a problem I think.
    I do not expect anyone to provide code to do all of this but some general pointers would be extremely helpful as I do not know if I'm thinking on the right track for any of this. Having some (limited) experience with Swing I doubt there is a simple way to do this but I can only hope!
    Thanks.
    Chris

    http://www2.gol.com/users/tame/swing/examples/SwingExamples.html
    there you can find some examples with CellRenderer's and so on ...
    have fun

  • Row Selection problem in custom cell renderer

    Hi,
    I have created a custom cell renderer to set color in my table based on some value and the screen also shows colors when i set this cell renderer.
    But, I am not able to see the row selection ie. with blue background when I select any row in the table is nor appearing. Can you tell me how to solve this problem.
    Regards,
    R.Vishnu Varadhan.

    Check out this [url http://forum.java.sun.com/thread.jsp?forum=57&thread=507001]thread for a similiar example.

  • JTree as cell renderer for JList

    I have an application that requires to display a list of tree-structured data.
    So I've used JTree a the cell renderer for the JList, and I can see a list of trees with that data in.
    However, the Jtree doesn't respond to Mouse messages, even if I dispatch the to it manually. So the tree is essentially dead.
    Does anybody know how to fix this?

    I'm not sure if they have the same thing for lists though.Yes, it is so - a cellrenderer or celleditor is a component, that is only there during it is used - a cellrenderer is there as long as it needs to paint the contents, a celleditor is there, if an edit-process is invoked and it will get messages as long as the editing process continues - after finishing editing, the component is no longer there - normally the renderer is called after that, to render the new contents into the rectangle of that cell, because the contents in its non-editing state may look other than that from the editor during the editing-state.
    greetings Marsian

  • Customized table cell renderer doesn't work after table data model changed

    Hi:
    I have a jtable with a custimized table cell render (changes the row color). Everything works fine while the data model is unchanged. I can change the row color, etc. However, after I delete one row or any number of rows in the table, the data model is updated and the custmized table cell renderer is not being called anymore while jtable is rendering on its cells. Seems like the table cell render is no long associated with the jtable. Is this a known problem? Any help would be appreciated.
    Thanks

    I am having the same problem. Has anybody solved this issue?
    Thanks

  • JList or JTree Cell Renderer

    hi. im doing a scheduler application
    wherein a list is displayed and when user post
    a scheduled activity, a textbox will be painted
    on top of the list, so that you could do away with
    overlapping schedules(2 or more schedule with
    the same time interval/s). Much like as that of
    the MS Outlook calendar.
    Can anyone post a snippet of the code of the
    cell renderer? im having a hard time studying
    cell rendering.
    thank you very much.

    Pls i badly nedd your help. somebody knowledgable on this?

  • Custom cell renderer.

    Folks,
    I have written a small custom defined cell renderer which displays
    a list
    When the first item is selected,the focus turns to red
    When the 2nd item is selected,1 and 2 items turn to red.
    (Obviously as I am setting the background to red)
    I just need to change the color of the focus element only.
    ie when i click the 1st element,focus changes to red.
    when i click the 2nd element,only the 2nd element becomes red and not the 1st and 2nd element
    class FTRDListCellRenderer extends JLabel implements ListCellRenderer {
    private final JLabel label = new JLabel();
      label.setOpaque(true);
      public Component getListCellRendererComponent(
      JList list, Object value,int index,
      boolean isSelected, boolean cellHasFocus) {
      label.setText(value.toString());
      if(isSelected){
      label.setBackground(isSelected ? Color.red : Color.yellow);
       else{
       return label;

    xpost
    http://forum.java.sun.com/thread.jsp?forum=31&thread=490864&tstart=0&trange=15

  • JTree cell renderer: how to fill whole row?

    hi,
    i'm trying to make a tree cell renderer that renders at default height, but fills the horizontal width of the tree (e.g. with a JLabel with a custom background color). I'm working on the theory that in order to do this you need to change the preferred size of the component used to stamp the image at render time.
    The problem is that the preferred width then needs to be set to a value that depends on the context of the particular node (e.g. a deeply nested child node will be further to the right than the root node).
    I can't seem to find a method to say where the rendering starts though - does anyone know a way?
    (also if not then would setting the width to some astronimcal value break anything?)
    thanks,
    asjf

    Try this one, it will higlight the background and foreground colors of entire rows.
    Oscar
         class TableRenderer
              extends DefaultTableCellRenderer
              implements ListCellRenderer
              private boolean focused = true;
              private JLabel renderer;
              public TableRenderer()
                   super();
                   renderer = new JLabel();
                   renderer.setOpaque(true);
              public Component getListCellRendererComponent(
                   JList list,
                   Object value,
                   int index,
                   boolean isSelected,
                   boolean cellHasFocus)
                   return renderer;
              public Component getTableCellRendererComponent(
                   JTable table,
                   Object value,
                   boolean isSelected,
                   boolean hasFocus,
                   int row,
                   int column)
                   renderer =
                        (JLabel) super.getTableCellRendererComponent(
                             table,
                             value,
                             isSelected,
                             hasFocus,
                             row,
                             column);
                   /* Make the Labels border empty and indented */
                   setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0));
                   /* This is used to create alternate row colors */
                   Color bgColor = Color.white;
                   if (row % 2 == 0)
                        bgColor = new Color(237, 243, 254);
                   /* if the table has focus and the row is selected use these colors */
                   if (table.hasFocus() && table.getSelectedRow() == row)
                        table.setSelectionForeground(Color.WHITE);
                        table.setSelectionBackground(new Color(101, 137, 178));
                   /* if the table has not the focus but the row is selected use these colors */
                   else if (
                        table.hasFocus() == false && table.getSelectedRow() == row)
                        table.setSelectionBackground(new Color(196, 196, 194));
                   /* if not use the standard color */
                   else
                        renderer.setBackground(bgColor);
                        table.setSelectionForeground(SystemColor.textText);
                   if (value instanceof ColorData)
                        ColorData cvalue = (ColorData) value;
                        setForeground(cvalue.color);
                        setText(cvalue.data.toString());
                                /* Set the Labels value */
                   setText(String.valueOf(value));
                   return renderer;
         }

Maybe you are looking for