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

Similar Messages

  • 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

  • Custom Cell Renderer for JTable

    Help, I'm trying to write a custom renderer for a column of my JTable but can't get it to work.
    Want I want is a cell in that column to be a label with an Icon and text.
    Trying to test with something simple, just changing colors but even that doesn't work. Can anyone see where I've gone wrong.
    table = new JTable(tableModel);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setShowGrid(false);
    TableColumn tc = table.getColumnModel().getColumn(0);
    tc.setCellRenderer(new DefaultTableCellRenderer() {
       public Component getTableCellRendererComponent(JTable table,
                                                   Object value,
                                                   boolean isSelected,
                                                   boolean hasFocus,
                                                   int row,
                                                   int column)
             JLabel label = (JLabel)
                super.getTableCellRendererComponent
                   (table, value, isSelected, hasFocus, row, column);
                label.setForeground(Color.red);
                label.setBackground(Color.black);
                System.out.println("Object: "+ value);
                return label;
    });Thanks,
    Derek

    Hi
    For colors try :
    all your code
    but where you call super.getTableCellRendererComponent(......
    do only setText(value.toString());
    I supose it is Ok just for changing the colors. If you want render
    an Icon plus some text you can put at your model a JLabel and at this
    render do
    setText((JLabel)value.getText());
    setIcon((JLabel)value.getIcon());
    inside a try/catch clause becasue you can put other kind of object at
    model level
    Or pass instances of an special Class with Icon/Text with publics members set/get to acces to text/icon.
    Hope this help

  • JTable custom cell renderer for each cell

    Hi,
    Iam trying to implement a JTable in which each cell in a column can be of a different type. i.e it can be a tree node or plain text. Can someone point me to examples where this has been done.
    Iam trying to override getColumnClass but it only takes a column no as parameter. I would like to return a different type depending on the row for which getColumnClass is called. It would help if getColumnClass could take 2 params (row and column). Can someone help.
    Cheers,
    vidyut

    You can override getCellRenderer(int row, int column) of JTable

  • Custom cell Renderer for datagrid

    For a long while now (way too long) I've being searching for
    a decent example for using components such as a checkbox or
    combobox inside of a datagrid.
    The only examples that i could find where all AS2 examples.
    The closest thing I find to an AS3 example for adding checkboxes,
    buttons etc to a datagrid was here
    http://www.adobe.com/devnet/flash/quickstart/datagrid_pt3/
    but it is in no way clear how to alter the example for other
    components.
    Could somebody please please please show me a working example
    of how to add a checkbox / button to a datagrid using flash cs3

    TypeError: Error #2007: 参数 text
    不能为空。
    at flash.text::TextField/set text()
    at fl.controls::LabelButton/set label()
    at xttmo::MyRowBgColorRender/set listData()
    at fl.controls::DataGrid/drawList()
    at xttmo::MyDataGrid/drawList()
    at fl.controls::DataGrid/draw()
    at fl.core::UIComponent/callLaterDispatcher()
    TypeError: Error #1009:
    无法访问空对象引用的属性或方法。
    at fl.controls::ComboBox/addCloseListener()
    TypeError: Error #2007: 参数 text
    不能为空。
    at flash.text::TextField/set text()
    at fl.controls::LabelButton/set label()
    at xttmo::MyRowBgColorRender/set listData()
    at fl.controls::DataGrid/drawList()
    at xttmo::MyDataGrid/drawList()
    at fl.controls::DataGrid/draw()
    at fl.core::UIComponent/callLaterDispatcher()
    TypeError: Error #1009:
    无法访问空对象引用的属性或方法。
    at fl.controls::ComboBox/close()
    at fl.controls::ComboBox/focusOutHandler()
    TypeError: Error #2007: 参数 child
    不能为空。
    at flash.display::DisplayObjectContainer/addChildAt()
    at fl.controls::BaseButton/drawBackground()
    at fl.controls::BaseButton/draw()
    at fl.core::UIComponent/callLaterDispatcher()
    package xttmo{
    import fl.controls.CheckBox;
    import fl.controls.listClasses.ICellRenderer;
    import fl.controls.listClasses.ListData;
    import flash.display.Graphics;
    import flash.display.Shape;
    import flash.events.MouseEvent;
    import flash.events.Event;
    import fl.core.InvalidationType;
    public class MyCheckboxRender extends CheckBox implements
    ICellRenderer {
    private var _data:Object;
    private var _listData:ListData;// column row
    protected var textOverlay:Shape;
    override public function dispatchEvent(event:Event):Boolean
    if (event.type==MouseEvent.CLICK) {
    setSelected1();
    return super.dispatchEvent(event);
    public function MyCheckboxRender():void {
    super();
    this.label="";
    this.move(0, 0);
    this.setSize(23, 22);
    var _t:MyCheckboxRender=this;
    this.addEventListener(MouseEvent.CLICK,
    function(e:MouseEvent):void{;
    _t.setSelected1();
    public function set data(item:Object):void {
    _data=item;
    // name = "sex";
    public function get data():Object {
    return _data;
    /*override public function set selected(value:Boolean):void
    {// this._selected=value;
    public function setSelected1():void {
    this._selected=Boolean(! this._selected);
    public override function get selected():Boolean {
    invalidate(InvalidationType.STATE);
    return _selected;
    private function myDraw():void {
    graphics.lineStyle(1, 0xB7BABC);
    var h:uint=19;// height;
    graphics.moveTo(0, -1),
    graphics.lineTo(0, h);
    graphics.lineTo(width, h);
    this.textField.text=_data["sex"];
    this._selected=Boolean(1==_data["sex"]);
    public function set listData(item:ListData):void {
    _listData=item;
    myDraw();
    public function get listData():ListData {
    return _listData;
    override protected function drawBackground():void {
    if (_listData.index%2==0) {
    setStyle("upSkin", CellRenderer_upSkinGray);
    } else {
    setStyle("upSkin", CellRenderer_upSkin);
    super.drawBackground();

  • 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

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

  • 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

  • Using JScrollpane via Custom Cell Renderer.Please Help

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

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

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

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

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

  • Row Selection problem in custom cell renderer

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

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

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

  • 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

  • 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

Maybe you are looking for

  • Keyword Tags Won't Delete

    I am using Lightroom 1.4.1 on a Vista platform.<br /><br />When I delete keyword tags they disappear temporarily, only to reappear later. I have tried the Purge Unused Keywords function and I have tried to right click the keyword and select Delete. I

  • Screensaver does not end after specified time

    i am running 10.6.4 on a 2008 Mac Pro. i have set the "flurry" screensaver to start after 5 minutes of inactivity, and set the display to go to sleep after 10 minutes. The screensaver starts after 5 minutes but does not turn off after 10 minutes, it

  • Error on table.

    Hello People, I am trying to retive the data from one of my archive table but its showing table or view does not exist although table is in our schema. and its daily exported into the export file. My table name is "tbltransactionlogarchivejul08" and

  • 47'' LG LCD TV

    We just bought a 47'' LG LCD TV and have noticed that sometimes there will be almost a blur around a person moving fast across the screen.  Does anyone know if this is a tv issue or a cable company issue? Thanks

  • Being driven crazy

    I'm going crazy trying to get exim to do what I want it to. Basically, every mail that I send (locally to myself) is being frozen. I CAN send with php sendmail. I can hardly find any info at all on this, so I'm not even sure if exim is the right prog