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

Similar Messages

  • 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

  • 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 table cell renderer in a JTable is not called

    Hello, all,
    I have the following task: I need to select several cells in a column, change the value of those cells, and once the value changes, the color of these cells should change as well. I wrote a custom cell renderer, and registered it for the object type that will use it to render the cell. However, the custom cell renderer is never called. Instead, the class name of the object is displayed in the cell.
    My code snippents are as follows:
    //Declare the table and add custom cell renderer
    JTable table = new JTable (7,7);
    table.setCellSelectionEnabled (true);
    table.setSelectionMode (ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    //Add the custom cell renderer to render objects of type Item
    table.setDefaultRenderer(Item.class, new CustomTableCellRenderer());
    //Get the selected cells and change the object type in those cells
    //This part works, since I see the app entering the for loop in the debugger, and the item.toString() value is displayed in each selected cell
    int rowIndexStart = table.getSelectedRow();
    int rowIndexEnd = table.getSelectionModel().getMaxSelectionIndex();
    int colIndex = table.getSelectedColumn();
    Item item = new Item ();
    for (int i = rowIndexStart; i<=rowIndexEnd; i++){
                  table.setValueAt(item, i, colIndex);
                 //I expect the cell to redraw now using custom cell renderer defined below, but that cell render is never called.  Instead, the item.toString() value is displayed in the cell.   What is wrong?
    //Definition of custom cell renderer. 
    //the getTableCellRendererComponent is never called, since the System.out.println never prints.  I expected this method to be called as soon as the Item object is added to the cell.  Am I wrong in expecting that?
    class CustomTableCellRenderer extends DefaultTableCellRenderer  {
        public Component getTableCellRendererComponent (JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            Component cell = super.getTableCellRendererComponent (table, value, isSelected, hasFocus, row, column);
            System.out.println("value: "+value.getClass()+" isSelected "+isSelected+" hasFocus "+hasFocus+" row "+row+" col "+column);
            if (this.isFocusOwner()) {
            cell.setBackground( Color.red );
            cell.setForeground( Color.white );
            return cell;
    } Please, help,
    Thank you!
    Elana

    The suggestion given above assumes that all the data in a given column is of the same type.
    If you have different types of data in different rows the you should be overriding the getCellRenderer(...) method. Something like:
    public TableCellRenderer getCellRenderer(int row, int column)
        Object o = getValueAt(row, column);
        if (o instanceof Item)
            return yourCustomRenderer
        else
            return super.getCellRenderer(row, column);
    }

  • Custom Table Cell Renderer Unable To Set Horizontal Alignment

    Hello,
    I have a problem that I'm at my wit's end with, and I was hoping for some help.
    I need to render the cells in my table differently (alignment, colors, etc) depending on the row AND the column, not just the column. I've got this working just fine, except for changing the cell's horizontal alignment won't work.
    I have a CustomCellRenderer that extends DefaultTableCellRenderer and overrides the getTableCellRendererComponent() method, setting the foreground/background colors and horizontal alignment of the cell based on the cell's value.
    I have a CustomTable that extends JTable and overrides the getCellRenderer(int row, int column) method to return a private instance of this CustomCellRenderer.
    This works fine for foreground/background colors, but my calls to setHorizontalAlignment() in the getTableCellRendererComponent() seem to have no effect, every cell is always displayed LEFT aligned! It's almost like the cell's alignment is determined by something else than the table.getCellRenderer(row,column).getTableCellRendererComponent() method.
    I've also tried setting the renderer for every existing TableColumn in the TableModel to this custom renderer, as well as overriding the table's getDefaultColumn() method to return this custom renderer as well for any Class parameter, with no success.
    No matter what I've tried, I can customize the cell however I want, EXCEPT for the horizontal alignment!!!
    Any ideas???
    Here's the core custom classes that I'm using:
    class CustomTable extends JTable {
    private CustomRenderer customRenderer = new CustomRenderer();
    public CustomTable() {
    super();
    public TableCellRenderer getCellRenderer(int row, int column) {
    return customRenderer;
    } // end class CustomTable
    class CustomRenderer extends DefaultTableCellRenderer {
    public CustomRenderer() {
    super();
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    if (row % 2 == 0) {
    setForeground(Color.red);
    setHorizontalAlignment(RIGHT);
    } else {
    setForeground(Color.blue);
    setHorizontalAlignment(LEFT);
    return this;
    } // end class CustomRenderer
    Even worse, I've gotten this to work fine in a trivial example I made to try and re-create the problem. But for some reason, this same thing is just not working for horizontal alignment in my actual project?!?
    Anyone have any ideas how the cell's horizontal alignment set in the getTableCellRendererComponent() method is being ignored or overwritten before the cell is being displayed???
    Thanks, any help is appreciated,
    -Alex Blume

    Ok, so I've looked into their source and I think I know where and what the trouble is. The JTable.java has a method called:
    3658> public TableCellRenderer getCellRenderer(int row, int column) {
    3659> TableColumn tableColumn = getColumnModel().getColumn(column);
    3660> TableCellRenderer renderer = tableColumn.getCellRenderer();
    3661> if (renderer == null) {
    3662> renderer = getDefaultRenderer(getColumnClass(column));
    3663> }
    3664> return renderer;
    3665> }
    starting at line 3658 of their source code. It retrieves the TableCellRenderer on line 3660 by calling the tableColumn's getCellRenderer method. This is found in the TableColumn.java class:
    421> public TableCellRenderer getCellRenderer() {
    422> return cellRenderer;
    423> }
    See the problem? Only ONE cell Renderer. It's referring to a variable found at line 140 which is of type TableCellRenderer ... well actually it's created as a DefaultTableCellRenderer at some point since TableCellRenderer is an interface.
    Basically the fix is this:
    In the TableColumn.java file, a collection (Vector, LinkedList, whatever) needs to keep track of each cell's renderer. This will solve the solution. Of course this will be something that you or I can make.
    What's funny is the contradiction in documentation between JTable's and TableColumn's getCellRenderer() method. First, if we look at TableColumn's documentation it states:
    "Returns the TableCellRenderer used by the JTable to draw values for this column."
    Based on that first statement, the getCellRenderer() method in TableColumn is doing its job exactly. No lies, no contradictions in what it does.
    However, that method is called up inside of the JTable's getCellRenderer() method which says a completely different thing which is:
    "Returns an appropriate renderer for the cell specified by this row and column."
    Now we have a problem. For the cell specified. It appears that the rush to push this out blinded some developer who either:
    1) mis-interpreted what the JTable getCellRenderer() method was supposed to do and inadvertently added a feature or;
    2) was in a 2 a.m. blitz, wired on Pepsi and adrenalin and wrote the bug in.
    Either way, I'm really hoping that they'll fix this because it will take care of at least 2 bugs. Btw, anyone interested in posting a subclass to solve this problem (subclass of TableColumn) is more than welcome. I've spent much too much time on this and my project is already behind so I can't really afford any more time on this.
    later,
    a.

  • Custom Jtree Cell Renderer goes to infinite loopp...any suggestion???

    Hey ...thanks for you help before....
    Another problem..
    My Jtree works fine with default Cell Renderer .. but goes to infinite
    loop with CustomDefaultRenderer after few minutes...
    Any suggestions....
        public DynamicTree() {
            super(new GridLayout(1,0));
            rootNode = new DefaultMutableTreeNode("POSTINGS & SEARCHES");
            treeModel = new DefaultTreeModel(rootNode);
            treeModel.addTreeModelListener(new MyTreeModelListener());
            tree = new JTree(treeModel);
            tree.setEditable(false);
            tree.getSelectionModel().setSelectionMode
                    (TreeSelectionModel.SINGLE_TREE_SELECTION);
            tree.setShowsRootHandles(true);
      //      tree.addMouseListener(ml);
      //      tree.addKeyListener(kl);
            JScrollPane scrollPane = new JScrollPane(tree);
            add(scrollPane);
            //          tree.setCellRenderer();
            tree.addTreeSelectionListener(new TreeSelectionListener(){
                public void valueChanged(TreeSelectionEvent evt){
                    System.out.println("Tree's lead selection path is " +
                            tree.getLeadSelectionPath());
            tree.setCellRenderer( new CustomDefaultRenderer());              
    public class CustomDefaultRenderer extends DefaultTreeCellRenderer {
        String suffix = null ;
        String prefix = null ;
        boolean expired = false;
        boolean matched = false ;
        PostingHandler pHandler = new PostingHandler();
        public Component getTreeCellRendererComponent(
                JTree tree,
                Object value,
                boolean sel,
                boolean expanded,
                boolean leaf,
                int row,
                boolean hasFocus) {
            super.getTreeCellRendererComponent(
                    tree, value, sel,
                    expanded, leaf, row,
                    hasFocus);
            suffix = (String)value.toString() ;
            try {
                prefix = value.toString().substring(0,value.toString().indexOf(":") + 1);
                suffix = suffix.substring(suffix.indexOf(":")+1,suffix.length());
                System.out.println("Prefix:"+prefix +"\tSufix :"+suffix);
            }catch (Exception e){System.out.println("Nothing to index yet" + e);}
            //    value = (Object)suffix;
            if(pHandler.newPostingsMatch.contains(prefix)) {
         //            if(hasFocus){pHandler.removePostingMatch(prefix);}               
                         setBackgroundNonSelectionColor(Color.CYAN);
            }else
                setBackgroundNonSelectionColor(Color.WHITE);
            System.out.println("Other <>values:\tValue" + value.toString() + "\tSEL:"+sel +"\tExpanded:" + "\tLEAF:"+leaf +
                    "\tRow:" +row + "\tfocus:"+hasFocus );
            return this;
        public void paintComponent(Graphics g){
            System.out.println("Paint is called");
            //g.drawLine(0, 0, 100, 100);
            if(expired){
                g.drawLine(22, 11, 100,11);
            g.drawString(suffix, 22,15);
            validate();
            repaint();
    }

    Figured it out right after this post :)
    I had to do the following in my cellrenderer
    setBackgroundNonSelectionColor(new Color(0, 0, 0, 0));As a parameter I sent a color object with a alpha level of 0 (completly transparent)...

  • 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

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

  • Selection of Custom JTable cell renderer inconsistenent between LAFs

    Sorry if that seems cryptic, but I don't know if I've run into a bug or not. I've recently switched from windows to linux and have noticed a problem with one of my programs. I have a "multiline" renderer that I made for my JTable. The renderer isn't terribly elegant, but when I'd select the row of the table, I made the multi-line renderer change its colors in response to the selection.
    This color selection switching works fine under the Metal LAF and the Windows LAF. However, this no longer works in the default look and feel is for linux (GTK+???). My multiline renderer in the JTable won't change its foreground/background in response to selection, but will if I use the Metal LAF under linux.
    Any idea what I'm doing wrong? Is this a bug? (I'm fairly certain I'm doing something silly, I just can't see it for the life of me).
    Here's the code I use to update the selection:
    class MultilineRenderer extends JTextArea
            implements TableCellRenderer {
        public MultilineRenderer(){
            super();
            setWrapStyleWord(false);
            setLineWrap(true);
            setFont(Const.TABLE_FONT);
            setOpaque(true);
        public Component getTableCellRendererComponent(
                JTable table, Object text,
                boolean isSelected, boolean hasFocus,
                int row, int column) {
            String data = (String)text;
            setText(data);
            if (isSelected){
                setForeground(table.getSelectionForeground());;
                setBackground(table.getSelectionBackground());
            } else {
                setForeground(table.getForeground());
                setBackground(table.getBackground());
            return this;
    }

    Some look and feels will ignore calls to setBackground and setForeground, and will instead decide their own colour.
    To quote the API documentation:
    "The background color affects each component differently and the parts of the component that are affected by the background color may differ between operating systems."
    I would imagine that this is your problem. Annoying, I know!

  • 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

  • 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

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

  • 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

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

Maybe you are looking for

  • Unable to reorder/change column names on interactive single row view

    I have created an interactive report and grouped my columns to display nicely in a single row view report. However, once I initially add the columns to a group, I am unable to reorder them. I can move them up and down the list, but the changes don't

  • Enhancements to Smartview wish list

    I know the Smartview team is working hard to enhance the product and based on the presentation Toufic gave at Kaleidoscope last year, I look forward to seeing all the changes. I aslo saw a post from Matt that says the team monitors the board and with

  • Unable to ping IP address from SG300 -10p switch

     i have two core switches, we have configured the vlan 70 in both core switch sh run int vlan 70 --ip address: 182.94.177.34/28 configured the HSRP in both routers. we have configured port in vlan 77 in access switch 4507R-E , we are able to ping the

  • Using JDBC Data Sources with ADFBC, NoInitialContextException

    Using JDBC Data Sources with ADF Business Components, NoInitialContextException I follow the instruction in the link below to create an ADF Swing application using datasource. I am using JDeveloper version 10.1.3. http://www.oracle.com/technology/pro

  • SOAP senario

    Hi Experts, My scenario is SAP R/3 is triggering an FM and receiver is SOAP adapeter(Sync interface) and my target url is http://xxx and scenario is working fine and my new requirement is to change target url from  http to https  in this case what I