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.

Similar Messages

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

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

  • Help with JTreeTable custom cell renderer!

    Hi.
    I've followed diligently the complete TreeTable2 example found on the Sun site. http://java.sun.com/products/jfc/tsc/articles/treetable2/
    What I'm trying to do is to add alternate-row shading on the Column(0) of the JTreeTable where the Column class is "TreeTableModel".
    so, from the example, I've added the following setCellRenderer declaration to TreeTableExample2.java:
         protected JTreeTable createTreeTable() {
              JTreeTable       treeTable = new JTreeTable(model);
              treeTable.getColumnModel().getColumn(1).setCellRenderer
              (new IndicatorRenderer());
              treeTable.getColumnModel().getColumn(0).setCellRenderer
              (new MyTableCellRenderer());Then, I subclass DefaultTableCellRenderer as shown below, in a new class called "MyTableCellRenderer"
    import java.awt.Color;
    import java.awt.Component;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableCellRenderer;
    public class MyTableCellRenderer extends DefaultTableCellRenderer implements TableCellRenderer
         private static final long serialVersionUID = 1L;
         public MyTableCellRenderer() {
         public Component getTableCellRendererComponent(JTable jtable, Object obj, boolean isSelected, boolean hasFocus, int i, int j)
              if (i % 2 == 0 && !isSelected) {
                   this.setBackground(new Color(214,226,255));
                   this.setForeground(Color.BLACK);
              } else if (isSelected)
                   this.setBackground(new Color(204, 204, 255));
              else {
                   this.setBackground(Color.white);
              //if (obj != null)
              this.setValue(obj.toString());
              System.out.println("obj: " + obj.toString());
              System.out.println("obj type: " + obj.getClass().getName());
              return ((Component) (this));
    }I've been pulling out whatever few hairs I have left in my sparse scalp to get this working, but it's looking grim thus far.
    Here are links to screenshots of my progress, or lack thereof:
    Original Working TreeTable II
    http://www.pharmalytix.com/original_treetable.jpg
    My Not-working Tree Table II w/ Custom Cell Renderer
    http://www.pharmalytix.com/customtablecellrenderer_treetable.jpg
    thanks again - !!

    phew! finally got this sucker working. I had to retrieve the default rendererer of my TreeTable's TreeTableModel class column, which is the JTree and then, in its component-form, start mucking about with its stylings. The real black-hole of progress was caused by my brain imploding from not being able to understand that a "Component" was what represented the "thing" whose behaviour I wanted to alter, be it a Jtree node or Jtable cell.
              treeTable.getColumnModel().getColumn(0).setCellRenderer(new TableCellRenderer() {
                   public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
                        Component comp = treeTable.getDefaultRenderer(TreeTableModel.class).getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
                        if (row % 2 == 0 && !isSelected) {
                             comp.setBackground(new Color(214,226,255));
                             comp.setForeground(Color.BLACK);
                        } else
                             if (isSelected)
                                  comp.setBackground(new Color(204, 204, 255));
                             else {
                                  comp.setBackground(Color.white);
                        return comp;
              });In all of its ravishing glory:
    http://www.pharmalytix.com/alternateshading_treetable.jpg
    Edited by: DataHog on Nov 6, 2007 10:21 AM

  • Inconsistent behavior with Custom Cell Renderer

    I have two questions:
    Questions # 1.
    I have created a custom cell renderer for my JTable that changes color if the text property changes and the text contains the letter 'S'. Like
    so:
    class SchedRenderer extends DefaultTableCellRenderer{
    public SchedRenderer(){
    super();
    final Color c = scSelfCont.panelbg;
    this.setForeground(c);
    this.addPropertyChangeListener("text",new PropertyChangeListener(){
    public void propertyChange(PropertyChangeEvent e){
         boolean foundS=false;
         String text=e.getNewValue().toString();
         for(int i=0;i<text.length();i++)
         if(text.charAt(i)=='S'){
         foundS=true;
         break;
         if(foundS){
         SchedRenderer.this.setBackground(Color.red);
         SchedRenderer.this.setForeground(Color.red);
         else{
         SchedRenderer.this.setBackground(c);
         SchedRenderer.this.setForeground(c);
    99% of the time it works just fine. But occasionally the cell will revert back to its original color, and then back to the correct color after clicking somewhere entirely different. I set some breakpoints in the property change handler and it gets called quite frquently even if no change has been made. At first I thought this was a JDK bug, but I am now convinced that there simply must be a better way to do this, any ideas?
    Question # 2:
    Is there a simple way to change the color of an entire row without selecting it? Currently I am using Custom Cell Renderers to change
    colors of cells, but it seems like such an obtuse method. Is there a better way?
    Thanks in advance.
    Adrian Calvin

    I have two questions:
    Questions # 1.
    I have created a custom cell renderer for my JTable that changes color if the text property changes and the text contains the letter 'S'. Like
    so:
    class SchedRenderer extends DefaultTableCellRenderer{
      public SchedRenderer(){
        super();
        final Color c = scSelfCont.panelbg;
        this.setForeground(c);
        this.addPropertyChangeListener("text",new PropertyChangeListener(){
           public void propertyChange(PropertyChangeEvent e){
         boolean foundS=false;
         String text=e.getNewValue().toString();
         for(int i=0;i<text.length();i++)
           if(text.charAt(i)=='S'){
             foundS=true;
             break;
         if(foundS){
           SchedRenderer.this.setBackground(Color.red);
           SchedRenderer.this.setForeground(Color.red);
         else{
           SchedRenderer.this.setBackground(c);
             SchedRenderer.this.setForeground(c);
    [\code]
    99% of the time it works just fine.  But occasionally the cell will revert back to its original color, and then back to the correct color after clicking somewhere entirely different.  I set some breakpoints in the property change handler and it gets called quite frquently even if no change has been made.  At first I thought this was a JDK bug, but I am now convinced that there simply must be a better way to do this, any ideas? 
    Question # 2:
    Is there a simple way to change the color of an entire row without selecting it?  Currently I am using Custom Cell Renderers to change
    colors of cells, but it seems like such an obtuse method.  Is there a better way?
    Thanks in advance.
    Adrian Calvin

  • Row Selection problem in custom cell renderer

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

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

  • Performance decrease with custom cell renderer

    Hi,
    Finally, I have my cell renderer working fine (it was simpler than I thought). Anyway, I'm suspecting something is not working quite well yet. When I try to reorder my colums (by dragging them) they move like slow motion. If I don't register my custom cell renderer, I can move my columns fine. Next is the code of my custom renderer.
    class PriorityRenderer extends DefaultTableCellRenderer {   
      public Component getTableCellRendererComponent(
      JTable table, Object value,     boolean isSelected,
      boolean hasFocus, int row, int column) {              
        if(value instanceof coloredValue) {
        coloredValue cv = (coloredValue)value;
        if(isSelected) this.setBackground(table.getSelectionBackground());
        else this.setBackground(cv.getbkColor());
        this.setForeground(cv.gettxColor());
        this.setText(value.toString());
        this.setOpaque(true);
        return this;
    }All the cells of my JTable are "coloredValue"s. This is a little class with a String, two colors and some getter methods.
    Can anyone giveme a hint ?
    Thanks!!

    OK! Now the performance problem is gone!! (I don't know why, I didn't touch a thing)
    Thanks anyway

  • TableSorter + custom cell renderer: how to get DISPLAYED value?

    Hi!
    I have a JTable with a custom cell renderer. This renderer translates numerical codes, which are stored in the table model, into textual names. E.g. the table model stores country codes, the renderer displays the name of the country.
    Now, having a reference on the JTable, how can I get the DISPLAYED value, i.e. the country name? Is there some method like ....getRenderer().getText()?
    Thanx,
    Thilo

    Well, a renderer can be anything. It may be rendering an image not text so you can't assume a method like getText(). However, since you know the component being used to render the cell you should be able to do something like:
    TableCellRenderer renderer = table.getCellRenderer(row, column);
    Component component = table.prepareRenderer(renderer, row, column);
    Now you can cast the component and use get text.
    Another option would be to store a custom class on the table cell. This class would contain both the code and value. The toString() method would return the value. Whenever you want the code you would use the table.getValueAt(...) method and then use the classes getCode() method. Using this approach you would not need a custom renderer. This thread shows how you can use this approach using a JComboBox, but the concept is the same for JTable as well:
    http://forum.java.sun.com/thread.jsp?forum=31&thread=417832

  • 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 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 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 Renderer and JTable

    Hello all,
    here is what i am trying to do. i want that when a user clicks on a cell the
    color of the cell should change to say red. when the user clicks on the other
    cell the red color in the first cell should remain.
    the way i am trying do to this is by making an object which contains an on and
    off state. based on click ie valuechanged() method in table
    based on the row and column i change the value of the boolean state on. my
    custom cell renderer checks whether the state is on or off
    and then changes the color.
    rightnow I am able to change the color on click but am unable to retain the
    color. so how can i retain the color.
    // making table
              vectorForSingleRow.add(0, "");                    
              vectorForSingleRow.add(1, new CellColorObject(TEXT_EDITOR));     
              Vector tempVectorForSingleRow = new Vector(vectorForSingleRow);               
              tempVectorForSingleRow.set(0, name);     
              vectorForSingleRow.set(1, new CellColorObject(TEXT_EDITOR));          
              data.add( tempVectorForSingleRow ); // data is a vector
              myTableModel = new DefaultTableModel(data, columnNames)
              //Customrenderer
              public Component getTableCellRendererComponent(JTable table, Object value,      
                                                     boolean isSelected, boolean hasFocus, int row, int column) {
              CellColorObject myObj = (CellColorObject)value;
              this.setText(value.toString());
                   System.out.println("value.getClickedStatus() " + myObj.getClickedState());
                   if(myObj.getClickedState()){
                        System.out.println("in 2");     
                        this.setBackground(Color.PINK);
                   if(isSelected){
                   System.out.println("in 1");
                   this.setSelected(true);
    // other things and end of method
    //custom object for storing state of the cell                                   
    public class CellColorObject{
         private String name = "";
         private boolean clickedState = false;
         public CellColorObject(String incomingName){
              name = incomingName;
         public void setClickedState(boolean newClickedState){
         System.out.println("setClickedState");
              clickedState = newClickedState;
         public boolean getClickedState(){
         System.out.println("getClickedState()");
              return clickedState;
         public String toString(){
              return name;
    // valueChanged method
           public void valueChanged(ListSelectionEvent e) {
             if (e.getValueIsAdjusting()) return;
              if(column == 1){
                   CellColorObject tempObj = (CellColorObject) myTable.getValueAt(row,column);
                   tempObj.setClickedState(true);
                   myTable.setValueAt(tempObj, row, column);
    // other things and method end
              

    You problem is that you are NOT setting the clickedState of your object:
    public Component getTableCellRendererComponent(JTable table, Object value,                                                       boolean isSelected, boolean hasFocus, int row, int column) {                         CellColorObject myObj = (CellColorObject)value;          this.setText(value.toString());                         System.out.println("value.getClickedStatus() " + myObj.getClickedState());               if(myObj.getClickedState()){                    System.out.println("in 2");                         this.setBackground(Color.PINK);               }               if(isSelected){               System.out.println("in 1");               this.setSelected(true);In the above, you have
    if (myObject.getClickedState())
    /// do code..
    notice you have:
    if (isSelected)
    this.setSelected(true);
    Maybe I am missing something, but I see no code that sets your objects clicked state when selected. My guess is that you should be doing value.setClickedState(true) when the thing is selected, something like:
    CellColorObject myObj = (CellColorObject)value;
    if (isSelected)
    myObj.setClickedState(true);
    else
    myObj.setClickedState(false);
    BUT, you didn't finish your code snippet within the method there, so perhaps you do this already?
    What you have should almost work, in that every single cell will call this method and if the object's clickedState is true, it should set the background color. Just make sure you are setting the objects clicked state.

  • 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

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

Maybe you are looking for