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

Similar Messages

  • 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?

  • 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

  • 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];
    }

  • 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).

  • 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

  • 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;
         }

  • Using JScrollpane via Custom Cell Renderer.Please Help

    Chaps,
    I have a question regarding scrolling of a JList.
    I have written a class (FTRDList) that has an Custom Cell Renderer.
    I want the list to be scrollable.
    This class is being called by many other classes.
    Now,as the FTRDList class is being called by many classes,i need
    to have all these classes to have the flwg statement
    add(new JScrollPane(FTRDList)),BorderLayout.CENTER);
    This can be a lot of work to chaneg all classes
    Rather,is it possible to have the JScrollPane built in the
    FTRDList class once and for all and let all classes call
    it by
    add(FTRDList,BorderLayout.CENTER);
    Please can anyone tell me how to make the FTRDList class Scrollable?
    Or is this not possible at all?
    Attached is the class:
    public class FTRDList extends JList {
        /* Inner class for Custom Cell Renderer */
        class MyCellRenderer extends JLabel implements ListCellRenderer {
        public Component getListCellRendererComponent(JList list,
                                                      Object value,            // value to display
                                                      int index,               // cell index
                                                      boolean isSelected,      // is the cell selected
                                                      boolean cellHasFocus) {  // the list and the cell have the focus
                setText(value.toString());
                if (isSelected) {
                setBackground(isSelected ? Color.red : Color.yellow);
             setForeground(isSelected ? Color.white : Color.black);
                setEnabled(list.isEnabled());
                setOpaque(isSelected);
                return this;
        public FTRDList() {
            super();
            setSelectedIndex(0);
            /** Invoke the cell Renderer */
            setCellRenderer(new MyCellRenderer());
            setOpaque(false);    

    I HAVE ALSO POSTED THIS IN THE JAVA PROGRAMMING FORUM PLEASE DONT GET OFFENDED AS I AM EXPECTING AN URGENT RESPONSEWell, someone has probably already answered this question in the Java forum, so I won't waste my time and answer it again here.

  • Drop mouse cursor disappears after setting custom cell renderer in table.

    Hi,
    I've a JList and a JTable, drag&drop works ok between them. Now, if I change TableCellRenderer to custom cell renderer, say a descendent of JComponent that implements TableCellRenderer, it doesn't display drag cursor when it's on top of a cell, and on 1 pixel grid lines it displays right again. can someone help me to fix this issue.
    Regards, thanks in advance,
    Ozgur

    it doesn't display drag cursor when it's on top of a cell, and on 1 pixel grid linesThe following renderer works ok for me, although I must admit there is a slight "flicker" when you move over the grid line. Not sure why that happens.
         class MultiLabelRenderer implements TableCellRenderer
              private JPanel panel;
              private JLabel red;
              private JLabel blue;
              public MultiLabelRenderer()
                   panel = new JPanel(new BorderLayout());
                   red = new JLabel();
                   red.setForeground(Color.RED);
                   blue = new JLabel();
                   blue.setForeground(Color.BLUE);
              public Component getTableCellRendererComponent(
                   JTable table, Object value, boolean isSelected,
                   boolean hasFocus, final int row, final int column)
                   String text = value.toString();
                   red.setText( text.substring(0,1) );
                   blue.setText( text.substring(1) );
                   panel.removeAll();
                   int columnWidth = table.getColumnModel().getColumn(column).getWidth();
                   int redWidth = red.getPreferredSize().width;
                   if (redWidth > columnWidth)
                        panel.add(red);
                   else
                        panel.add(red, BorderLayout.WEST);
                        panel.add(blue);
                   if (isSelected)
                        panel.setBackground( table.getSelectionBackground() );
                   else
                        panel.setBackground( table.getBackground() );
                   return panel;
         }

  • Custom Cell Renderer / Video garbage on "refresh"

    I have created a custom Cell Renderer for my JTable. When the application in which this JTable is displayed, is moved into the background and then brought back "front", The application does not redraw itself completely.
    I am able to see the information contained in the JTable but none of the surrounding components. When I do a mouse click on any of the background of the surrounding panel, nothing happens.
    In order to get the entire Panel/View/all visible components to refresh themselves, I have to click on aother component (example would be switching to a different panel of the tabbed pane.)
    This only happens when I have a JTable with this particular Renderer showing. Any other panel or JTable not using this Renderer refreshes completely.
    Here is my Cell Renderer most of which I borrowed extensively from info posted in these forums:
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.io.*;
    * This is a much lighter version of the multiline renderer.  It does need to have newline
    * characters at the points where the next line should occur.
    public class CTAuditTableCellRenderer extends JList implements TableCellRenderer {
        public CTAuditTableCellRenderer() {
            setOpaque(true);
            ListCellRenderer renderer = getCellRenderer();
            ((JLabel)renderer).setHorizontalAlignment(JLabel.CENTER);
            setCellRenderer(renderer);
        *   getTableCellRendererComponent() is the only method that must be over-ridden.
        *   @param table the JTable holding cell we wish to render
        *   @param value the object which we wish to put into the cell
        *   @param isSelected boolean to allow selected cell to appear as such
        *   @param hasFocus boolean to alert as to the cell having focus
        *   @param row row of the JTable in which cell resides
        *   @param column column of the JTable in which the cell resides.
        *   @return Component the image of the value object.  Not a true object but an
        *   image of the object.
        public Component getTableCellRendererComponent(JTable table, Object value,
                                    boolean isSelected, boolean hasFocus, int row, int column) {
            if (isSelected) {
                setForeground(table.getSelectionForeground());
                setBackground(table.getSelectionBackground());
            } else {
                setForeground(table.getForeground());
                setBackground(table.getBackground());
            setFont(table.getFont());
            if (hasFocus) {
                setBorder( UIManager.getBorder("Table.focusCellHighlightBorder") );
                if (table.isCellEditable(row, column)) {
                    setForeground( UIManager.getColor("Table.focusCellForeground") );
                    setBackground( UIManager.getColor("Table.focusCellBackground") );
            } else {
                setBorder(new EmptyBorder(1, 2, 1, 2));
            String str = (value == null) ? "" : value.toString();
            BufferedReader br = new BufferedReader(new StringReader(str));
            String line;
            Vector v = new Vector();
            try {
                while ((line = br.readLine()) != null) {
                    v.addElement(line);
            } catch (IOException ex) { ex.printStackTrace(); }
            setListData(v);
            if(v.size() > 1){
                table.setRowHeight(row, (table.getRowHeight()+ 3)* v.size());
            return this;
    }Thank you in advance for your constructive, insightful, and applicable replies.
    Jerry

    Here is an entire example that shows the situation of the Frame (in this case) not updating/refreshing all of it's components when regaining focus.
    To simulate the problem, simply move "something"/another window over the sample frame and then move it off. In my case the scrollbar and the headers do not reappear until I have selected a row and scrolled the table.
    Here is the example code:
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    public class MultiLineCellExample extends JFrame {
      MultiLineCellExample() {
        super( "Multi-Line Cell Example" );
        DefaultTableModel dm = new DefaultTableModel() {
          public Class getColumnClass(int columnIndex) {
            return String.class;
        dm.setDataVector(new Object[][]{{"aa aa aa aa aa\naa aa aa aa aa\naa aa aa aa aa","b","c"},
                                        {"A","B","C\nC"},{"x","y","z"}},
                         new Object[]{"1","2","3"});
        JTable table = new JTable( dm );
        table.setDefaultRenderer(String.class, new MultiLineCellRenderer());
        JScrollPane scroll = new JScrollPane( table );
        getContentPane().add( scroll );
        setSize( 400, 130 );
        setVisible(true);
      public static void main(String[] args) {
        MultiLineCellExample frame = new MultiLineCellExample();
        frame.addWindowListener( new WindowAdapter() {
          public void windowClosing( WindowEvent e ) {
            System.exit(0);
    }And here is the Renderer code:
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.io.*;
    public class MultiLineCellRenderer extends JList implements TableCellRenderer {
        public MultiLineCellRenderer() {
            setOpaque(true);
            ListCellRenderer renderer = getCellRenderer();
            ((JLabel)renderer).setHorizontalAlignment(JLabel.CENTER);
            setCellRenderer(renderer);
        public Component getTableCellRendererComponent(JTable table, Object value,
                                    boolean isSelected, boolean hasFocus, int row, int column) {
            if (isSelected) {
                setForeground(table.getSelectionForeground());
                setBackground(table.getSelectionBackground());
            } else {
                setForeground(table.getForeground());
                setBackground(table.getBackground());
            setFont(table.getFont());
            if (hasFocus) {
                setBorder( UIManager.getBorder("Table.focusCellHighlightBorder") );
                if (table.isCellEditable(row, column)) {
                    setForeground( UIManager.getColor("Table.focusCellForeground") );
                    setBackground( UIManager.getColor("Table.focusCellBackground") );
            } else {
                setBorder(new EmptyBorder(0, 0, 0, 0));
            String str = (value == null) ? "" : value.toString();
            BufferedReader br = new BufferedReader(new StringReader(str));
            String line;
            Vector v = new Vector();
            try {
                while ((line = br.readLine()) != null) {
                    v.addElement(line);
            } catch (IOException ex) { ex.printStackTrace(); }
            setListData(v);
            if(v.size() > 1){
                table.setRowHeight(row, (table.getRowHeight()+2)* v.size());
            return this;
    }Please, this is a very annoying problem and I would appreciate help in solving.
    Jerry

  • Custom cell rendering

    I have got a JList.
    And I am going to create my custom cell renderer which can show a label and a pic inline.
    How can I do it?

    Check out the tutorial at http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html#renderer

  • How to remove a cell renderer

    I have been looking through the apis and search but to no sucess. I have tried a few different remove methods but none seem to be working. Does anyone know how to remove a cell renderer.

    What do you mean "remove a cell renderer".
    What component or class are you talking about? I'm only aware of renderers being used by Swing components. If thats the case then the question should be posted in the Swing forum.
    What do you mean by remove? If you remove the renderer how would the cell be renderered. Do you mean that you want the cell to use the default cell renderer?
    What component are you talking about? I'm aware of renderers for JTree, JTable, JList, JComboBox.
    If I had to guess I would think you are talking about a JTable, so I would suggest simple setting the renderer to null for the particular column.
    If that doesn't work then you can always use the getDefaultRenderer(...) method and then reset the column that way?
    But you question is not very clear so Its a lot of guess work on my part.

  • Help reqd for 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
    Can any one please see the code I have written and suggest a change?
    class FTRDListCellRenderer extends JLabel implements ListCellRenderer {
                         public FTRDListCellRenderer(){
                      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

  • Problem with addRow and MultiLine Cell renderer

    Hi ,
    Ive a problem with no solution to me .......
    Ive seen in the forum and Ivent found an answer.......
    The problem is this:
    Ive a JTable with a custom model and I use a custom multiline cell renderer.
    (becuse in the real application "way" hasnt static lenght)
    When I add the first row all seem to be ok.....
    when I try to add more row I obtain :
    java.lang.ArrayIndexOutOfBoundsException: 1
    at javax.swing.SizeSequence.insertEntries(SizeSequence.java:332)
    at javax.swing.JTable.tableRowsInserted(JTable.java:2926)
    at javax.swing.JTable.tableChanged(JTable.java:2858)
    at javax.swing.table.AbstractTableModel.fireTableChanged(AbstractTableMo
    del.java:280)
    at javax.swing.table.AbstractTableModel.fireTableRowsInserted(AbstractTa
    bleModel.java:215)
    at TableDemo$MyTableModel.addRow(TableDemo.java:103)
    at TableDemo$2.actionPerformed(TableDemo.java:256)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:17
    64)
    at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(Abstra
    ctButton.java:1817)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel
    .java:419)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:257
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonL
    istener.java:245)
    at java.awt.Component.processMouseEvent(Component.java:5134)
    at java.awt.Component.processEvent(Component.java:4931)
    at java.awt.Container.processEvent(Container.java:1566)
    at java.awt.Component.dispatchEventImpl(Component.java:3639)
    at java.awt.Container.dispatchEventImpl(Container.java:1623)
    at java.awt.Component.dispatchEvent(Component.java:3480)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3165)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
    at java.awt.Container.dispatchEventImpl(Container.java:1609)
    at java.awt.Window.dispatchEventImpl(Window.java:1590)
    at java.awt.Component.dispatchEvent(Component.java:3480)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchTh
    read.java:197)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
    ad.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
    This seems to be caused by
    table.setRowHeight(row,(getPreferredSize().height+2)); (line 164 of my example code)
    About the model I think its ok.....but who knows :-(......
    Please HELP me in anyway!!!
    Example code :
    import javax.swing.*;
    import javax.swing.table.*;
    import java.text.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class TableDemo extends JFrame {
    private boolean DEBUG = true;
    MyTableModel myModel = new MyTableModel();
    MyTable table = new MyTable(myModel);
    int i=0;
    public TableDemo() {
    super("TableDemo");
    JButton bottone = new JButton("Aggiungi 1 elemento");
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    //table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this window.
    getContentPane().add(bottone,BorderLayout.NORTH);
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    bottone.addActionListener(Add_Action);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    class MyTable extends JTable {
    MultiLineCellRenderer multiRenderer=new MultiLineCellRenderer();
    MyTable(TableModel tm)
    super(tm);
    public TableCellRenderer getCellRenderer(int row,int col) {
              if (col==1) return multiRenderer;
              else return super.getCellRenderer(row,col);
    class MyTableModel extends AbstractTableModel {
    Vector data=new Vector();
    final String[] columnNames = {"Name",
    "Way",
    "DeadLine (ms)"
    public int getColumnCount() { return 3; }
    public int getRowCount() { return data.size(); }
    public Object getValueAt(int row, int col) {
    Vector rowdata=(Vector)data.get(row);
                                                                return rowdata.get(col); }
    public String getColumnName(int col) {
    return columnNames[col];
    public void setValueAt (Object value, int row,int col)
         //setto i dati della modifica
    Vector actrow=(Vector)data.get(row);
    actrow.set(col,value);
         this.fireTableCellUpdated(row,col);
         public Class getColumnClass(int c)
              return this.getValueAt(0,c).getClass();
         public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    if (col == 1)
    return false;
    else
    return true;
    public void addRow (String name,ArrayList path,Double dead) {
         Vector row =new Vector();
         row.add(name);
         row.add(path);
         row.add(dead);
         row.add(name); //!!!Mi tengo questo dato da utilizzare come key per andare a
         //prendere il path nella lista dei paths di Project
         //(needed as key to retrive data if name in col. 1 is changed)
         data.add(row);
         //Inspector.inspect(this);
         System.out.println ("Before firing Adding row...."+this.getRowCount());
         this.fireTableRowsInserted(this.getRowCount(),this.getRowCount());
    public void delRow (String namekey)
    for (int i=0;i<this.getRowCount();i++)
    if (namekey.equals(this.getValueAt(i,3)))
    data.remove(i);
    this.fireTableRowsDeleted(i,i);
    //per uscire dal ciclo
    i=this.getRowCount();
    public void delAllRows()
    int i;
    int bound =this.getRowCount();     
    for (i=0;i<bound;i++)     
         {data.remove(0);
         System.out.println ("Deleting .."+data);
    this.fireTableRowsDeleted(0,i);          
    class MultiLineCellRenderer extends JTextArea implements TableCellRenderer {
    private Hashtable rowHeights=new Hashtable();
    public MultiLineCellRenderer() {
    setEditable(false);
    setLineWrap(true);
    setWrapStyleWord(true);
    //this.setBorder(new Border(
    public Component getTableCellRendererComponent(JTable table,Object value,                              boolean isSelected, boolean hasFocus, int row, int column) {
    //System.out.println ("Renderer called"+value.getClass());
    if (value instanceof ArrayList) {
    String way=new String     (value.toString());
    setText(way);
    TableColumn thiscol=table.getColumn("Way");
    //System.out.println ("thiscol :"+thiscol.getPreferredWidth());
    //setto il size della JTextarea sulle dimensioni della colonna
    //per quanto riguarda il widht e su quelle ottenute da screen per l'height
    this.setSize(thiscol.getPreferredWidth(),this.getPreferredSize().height);
    // set the table's row height, if necessary
    //System.out.println ("Valore getPreferred.height"+getPreferredSize().height);
         if (table.getRowHeight(row)!=(this.getPreferredSize().height+2))
         {System.out.println ("Setting Row :"+row);
             System.out.println ("Dimension"+(getPreferredSize().height+2));
             System.out.println ("There are "+table.getRowCount()+"rows in the table ");
             if (row<table.getRowCount())
             table.setRowHeight(row,(getPreferredSize().height+2));
    else
    setText("");
    return this;
    /**Custom JTextField Subclass che permette all'utente di immettere solo numeri
    class WholeNumberField extends JTextField {
    private Toolkit toolkit;
    private NumberFormat integerFormatter;
    public WholeNumberField(int value, int columns) {
    super(columns);
    toolkit = Toolkit.getDefaultToolkit();
    integerFormatter = NumberFormat.getNumberInstance(Locale.US);
    integerFormatter.setParseIntegerOnly(true);
    setValue(value);
    public int getValue() {
    int retVal = 0;
    try {
    retVal = integerFormatter.parse(getText()).intValue();
    } catch (ParseException e) {
    // This should never happen because insertString allows
    // only properly formatted data to get in the field.
    toolkit.beep();
    return retVal;
    public void setValue(int value) {
    setText(integerFormatter.format(value));
    protected Document createDefaultModel() {
    return new WholeNumberDocument();
    protected class WholeNumberDocument extends PlainDocument {
    public void insertString(int offs,
    String str,
    AttributeSet a)
    throws BadLocationException {
    char[] source = str.toCharArray();
    char[] result = new char[source.length];
    int j = 0;
    for (int i = 0; i < result.length; i++) {
    if (Character.isDigit(source))
    result[j++] = source[i];
    else {
    toolkit.beep();
    System.err.println("insertString: " + source[i]);
    super.insertString(offs, new String(result, 0, j), a);
    ActionListener Add_Action = new ActionListener() {
              public void actionPerformed (ActionEvent e)
              System.out.println ("Adding");
              ArrayList way =new ArrayList();
              way.add(new String("Uno"));
              way.add(new String("Due"));
              way.add(new String("Tre"));
              way.add(new String("Quattro"));
              myModel.addRow(new String("Nome"+i++),way,new Double(0));     
    public static void main(String[] args) {
    TableDemo frame = new TableDemo();
    frame.pack();
    frame.setVisible(true);

    In the addRow method, change the line
    this.fireTableRowsInserted(this.getRowCount(),this.getRowCount()); to
    this.fireTableRowsInserted(data.size() - 1, data.size() - 1);Sai Pullabhotla

Maybe you are looking for