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?

Similar Messages

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

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

  • 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 to make JTree cell renderer respect layout?

    Hi,
    In the JTree tutorial, the first example TreeDemo shows a simple tree.
    http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html
    If you grab the frame and make it really thin, you get a horizontal scroll bar in the top pane.
    How can I make it so that the tree cells just draw "..." at the end of the string if there is not enough space?
    I know the tree cell renderer uses JLabel, but they never seem to show "...", which is one of the best features of a JLabel. Any help is greatly appreciated!

    Hi,
    I got it working, but I also discovered a Java bug that ruins all this effort!
    Calculating the node's position & width:
    - When child nodes are indented, there is an "L" shaped line drawn... the space to the left of the line's vertical bar is the "leftChildIndent", and the space to the right is the "rightChildIndent". So you add both to get the whole indent.
    - I use label.getPreferredSize().width to figure out the node width, since that includes the icon width, the icon-text gap, and the font metrics.
    Example program:
    - This program models how I want it to look... Always expanded and automatic "..." when the scroll pane is not big enough.
    Bug found:
    - There is a runnable example below. Just run it and after a couple seconds, move the split pane to the right.
    - I use a timer to add a new node every 1 second. The new nodes get stuck being too small, and the original nodes don't have this problem.
    // =====================================================
    * Adaptation of TreeDemo to allow for tree nodes that show "..."
    * when there is not enough space to display the whole label.
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JSplitPane;
    import javax.swing.JTree;
    import javax.swing.Timer;
    import javax.swing.UIManager;
    import javax.swing.event.TreeExpansionEvent;
    import javax.swing.event.TreeWillExpandListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.ExpandVetoException;
    import javax.swing.tree.TreeCellRenderer;
    import javax.swing.tree.TreeSelectionModel;
    public class TreeDemo extends JPanel {
        private JTree tree;
        protected class EllipsesTreeCellRenderer implements TreeCellRenderer {
            Integer leftIndent = (Integer) UIManager.get("Tree.leftChildIndent");
            Integer rightIndent = (Integer) UIManager.get("Tree.rightChildIndent");
            int indent = leftIndent.intValue() + rightIndent.intValue();
            JLabel label = new JLabel();
            DefaultTreeCellRenderer r = new DefaultTreeCellRenderer();
            public Component getTreeCellRendererComponent(JTree tree, Object value,
                    boolean selected, boolean expanded, boolean leaf, int row,
                    boolean hasFocus) {
                label.setText("why hello there why hello there why hello there");
                if (selected) {
                    label.setForeground(r.getTextSelectionColor());
                    label.setBackground(r.getBackgroundSelectionColor());
                } else {
                    label.setForeground(r.getTextNonSelectionColor());
                    label.setBackground(r.getBackgroundNonSelectionColor());
                if (leaf) {
                    label.setIcon(r.getLeafIcon());
                } else if (expanded) {
                    label.setIcon(r.getOpenIcon());
                } else {
                    label.setIcon(r.getClosedIcon());
                label.setComponentOrientation(tree.getComponentOrientation());
                int labelWidth = label.getPreferredSize().width;
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
                int level = node.getLevel();
                if (!tree.isRootVisible()) {
                    --level;
                int indentWidth = indent * level;
                int rendererWidth = labelWidth + indentWidth;
                // This is zero the first few times getTreeCellRenderer is called
                // because the tree is not yet visible.
                int maxWidth = (int) tree.getVisibleRect().getWidth();
                if (maxWidth > 0) {
                    if (rendererWidth > maxWidth) {
                        // figure out how much space "..." will consume.
                        label.setText(label.getText() + "...");
                        maxWidth = maxWidth
                                - (label.getPreferredSize().width - labelWidth);
                        label.setText(label.getText());
                        // chop off characters until "..." fits in the visible
                        // portion.
                        if (maxWidth > 0) {
                            while (rendererWidth > maxWidth
                                    && label.getText().length() > 1) {
                                label.setText(label.getText().substring(0,
                                        label.getText().length() - 2));
                                rendererWidth = indentWidth
                                        + label.getPreferredSize().width;
                            label.setText(label.getText() + "...");
                return label;
        public TreeDemo() {
            super(new GridLayout(1, 0));
            //Create the nodes.
            final DefaultMutableTreeNode top = new DefaultMutableTreeNode("");
            createNodes(top);
            //Create a tree that allows one selection at a time.
            tree = new JTree(top);
            tree.getSelectionModel().setSelectionMode(
                    TreeSelectionModel.SINGLE_TREE_SELECTION);
            tree.setCellRenderer(new EllipsesTreeCellRenderer());
            tree.addTreeWillExpandListener(new TreeWillExpandListener() {
                public void treeWillExpand(TreeExpansionEvent event) {
                public void treeWillCollapse(TreeExpansionEvent event)
                        throws ExpandVetoException {
                    throw new ExpandVetoException(event);
            for (int i = tree.getRowCount(); i >= 0; i--) {
                tree.expandRow(i);
            //Create the scroll pane and add the tree to it.
            JScrollPane treeView = new JScrollPane(tree);
            //Add the scroll panes to a split pane.
            JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
            splitPane.setTopComponent(treeView);
            splitPane.setBottomComponent(new JLabel(""));
            Dimension minimumSize = new Dimension(0, 0);
            treeView.setMinimumSize(minimumSize);
            splitPane.setDividerLocation(200); //XXX: ignored in some releases
            //of Swing. bug 4101306
            //workaround for bug 4101306:
            //treeView.setPreferredSize(new Dimension(100, 100));
            // Makes tree nodes appear cut-off initially.
            splitPane.setPreferredSize(new Dimension(500, 300));
            //Add the split pane to this panel.
            add(splitPane);
            // Adds a new node every 1 second
            Timer timer = new Timer(1000, new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
                    DefaultMutableTreeNode child = new DefaultMutableTreeNode("");
                    model.insertNodeInto(child, top, 0);
                    for (int i = tree.getRowCount(); i >= 0; i--) {
                        tree.expandRow(i);
            timer.start();
        private void createNodes(DefaultMutableTreeNode top) {
            DefaultMutableTreeNode category = null;
            DefaultMutableTreeNode book = null;
            category = new DefaultMutableTreeNode("");
            top.add(category);
            category.add(new DefaultMutableTreeNode(""));
            category.add(new DefaultMutableTreeNode(""));
            category.add(new DefaultMutableTreeNode(""));
            category.add(new DefaultMutableTreeNode(""));
            category.add(new DefaultMutableTreeNode(""));
            category.add(new DefaultMutableTreeNode(""));
            category.add(new DefaultMutableTreeNode(""));
            category.add(new DefaultMutableTreeNode(""));
            category.add(new DefaultMutableTreeNode(""));
         * Create the GUI and show it. For thread safety, this method should be
         * invoked from the event-dispatching thread.
        private static void createAndShowGUI() {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
                System.err.println("Couldn't use system look and feel.");
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("TreeDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            TreeDemo newContentPane = new TreeDemo();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

  • JTree Cell Renderer Default

    Hi all,
    I am trying to set up an option that will allow a user to change the JTree Icon image to their prefered choice, I have a number of different images that changes when I select on the JMenuItem selection, as I am calling the ActionListener to another class called Renderer(), like:
    tree.setCellRenderer(new Renderer());
    But what I am trying to do is to try to allow the user to select the java default icons, can anybody show me how this is done. Its being annoying me for ages.
    thanks all

    Hi all,
    I am trying to set up an option that will allow a
    user to change the JTree Icon image to their prefered
    choice, I have a number of different images that
    changes when I select on the JMenuItem selection, as
    I am calling the ActionListener to another class
    called Renderer(), like:
    tree.setCellRenderer(new Renderer());
    But what I am trying to do is to try to allow the
    user to select the java default icons, can anybody
    show me how this is done. Its being annoying me for
    ages.
    thanks allThis information can be retrieved from the UIDefaults in the UIManager. The keys are:
    Tree.closedIcon
    Tree.collapsedIcon
    Tree.drawsFocusBorderAroundIcon
    Tree.expandedIcon
    Tree.leafIcon
    Tree.openIcon
    To retrieve the Icon, something like the following should work:
    Icon closedIcon = UIManager.getDefaults().getIcon("Tree.closedIcon");Jim S.

  • JTree Cell Renderer Problem

    Hi can someone help me please??
    I've created a JTree with a custom TreeUI which paints the JTree's backround with gradient paint.
    The problem i'm having is that i want to make the background color of the treecells transparent, no color at all. In my custom TreeCellRenderer it works fine setting the foreground color and everything, but not the background...
    Any clues anyone?

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

  • JTree cell rendering

    All my tree nodes has an icon on the left and text on the right
    Just for a node or two, I need to put extra text on the right of the label text but in different color. What's the best way to do that?
    Would I have to change my renderer to not inherit DefaultTreeCellRenderer and inherit JPanel with TreeCellRenderer?
    Can I do it overwriting a paint function and check for that instance?
    Need a little example of doing extra work for a particular node that involves rendering in different colors...
    Thanks
    Abraham Khalil

    have you seen the demo tree renderer code here?
    http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html
    as long as you have some way of telling when you need to render differently then you can either pass back the default renderer's component (ie call the super classes method) or pass back a privately owned one.
    you could either use JLabels support of HTML for rendering the text in a different color, or maintain two instances of a JLabel on a JPanel and use that as the stamp
    asjf

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

  • JTree custom cell renderer question

    When using a custom cell renderer is their anyway to tell the offset of the current node?
    For example if you have a tree with the parent node "Parent" that has a few children nodes it will look something like this:
    Parent
    |----Child 1
    |----Child 2
    |----Child 3
    So the parent would have an offset of zero. I want to know how to get the childrens offset? If this is possible?
    What I am trying to accomplish:
    I have a JTree as a scrollpane rowHeader. While the main body of the scrollpane is a JTable. I need the tree's nodes to fill the entire width so that it looks like part of the table. I figure the row header width - current node offset should be the width that I will need each node to be. Any help is welcome. Thanks.

    the renderer tells you the row, the tree can get you a treepath for a row
    TreePath getPathForRow(int row)
    That can tell you the depth of the node.

  • 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

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

  • Event Handling in JTable Custom Cell Renderer

    I have a JLabel as a custom cell Renderer for a column. I want to handle mouse click event for the JLabel rendered in the cell.
    I tried adding the listener for the label in the custom cell renderer but it is not working. Any ideas how to handle this problem??
    Thanks
    S.Anand

    If you want to handle the selection of a tree node
    1) write a class like:
    public class TreePaneListener implements TreeSelectionListener {
    // TREE SELECTION LISTENER
    public void valueChanged(TreeSelectionEvent e) {
    JTree tree = (JTree)e.getSource();
    DefaultMutableTreeNode node = null;
    int count = 0;
    boolean doSomething = false;
    if(tree.getSelectionCount() > 1) {
         TreePath[] selection = tree.getSelectionPaths();
         int[] temp = new int[selection.length];
         for(int i =0; i < selection.length; i++) {
    // Check each node for selection
         node = (DefaultMutableTreeNode)selection.getLastPathComponent();
         if(node.getLevel()==2) {
    // Change this code to take the action desired
         doSomething = true;
    2) After creating the tree register the listener
    TreePaneListener handler = new TreePaneListener();
    tree.addTreeSelectionListener(handler);

Maybe you are looking for

  • Calendar events on iphone won't sync to ical on Mac since iphone 7.0.2 upgrade

    Help! Some events - but not every one -  entered into new Iphone SW 7.0.2 do not sync back to the Calendar (v 4.0.4 from ILife 2009).  I have tried rebooting my systems (computer and phone), as well as re-creating the problem by adding new test event

  • Adobe Reader for Android

    Hi, I am developing an android app. I need to be able to display a particular page from various pdf files based on a page no supplied by the app. Therefore I need to be able to pass this page no to the pdf reader and for the reader to display the rel

  • Understanding how Error handling works in transformation

    Hi Experts, I am trying to achieve error handling in Start and End Routine by writing the error log to the monitor and also raising the exception in case a match is not found. I understand the code below achieves what I am looking for, but I want to

  • Error Opening Oracle Terminal File fmrweb.

    I installed 9IAS portal and the forms/reports server. The portal works fine, but when I try the 'Run Form Web ( runform.htm)' I get an error "Error opening Oracle*Terminal file fmrweb." The file does exist in my c:\oracle\806\forms60 directory and my

  • Grant 1111. Error message when confirming goods

    Hi, After creating a PO I try to create a goods confirmation but I get the error message: <b>Grant 1111 does not exist</b>. As a second error message I also get the message: No approval workflow found. Inform system administrator. Is there anyone who