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

Similar Messages

  • JTable custom cell renderer and editor breaks row sorting

    Hello Forum,
    I have a JTable on which I set setAutoCreateRowSorter(true); I then hook up a custom cell editor and renderer for the Date class.
    this.tblLeden.setDefaultRenderer(Date.class, new DateCellEditor());
    this.tblLeden.setDefaultEditor(Date.class, new DateCellEditor());
    The sorting for that particular row then breaks, it works fine for every other row. How do I fix this? Just directions where to look would be great too.
    Here is my code for the renderer/editor:
    (btw this is probably not the best way to do this so any suggestions for optimizing are great too)
    import java.awt.Component;
    import java.util.Date;
    import java.util.EventObject;
    import java.util.HashMap;
    import java.util.Vector;
    import javax.swing.JTable;
    import javax.swing.event.CellEditorListener;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    import com.toedter.calendar.JDateChooser;
    public class DateCellEditor extends JDateChooser implements TableCellRenderer, TableCellEditor
      private static final long serialVersionUID = -5073758499524392257L;
      private final Vector<CellEditorListener> listeners = new Vector<CellEditorListener>();
      // oops.. lingering objects problem when rows are deleted..
      private final HashMap<Integer, JDateChooser> components = new HashMap<Integer, JDateChooser>();
      @Override
      public final Component getTableCellRendererComponent(final JTable table,
          final Object value, final boolean isSelected, final boolean hasFocus,
          final int row, final int col)
        JDateChooser temp = this.components.get(Integer.valueOf(row));
        if (temp == null)
          temp = new JDateChooser();
          this.components.put(Integer.valueOf(row), temp);
        temp.setDate((Date) value);
        return temp;
      @Override
      public final Component getTableCellEditorComponent(final JTable table,
          final Object value, final boolean isSelected, final int row,
          final int column)
        JDateChooser temp = this.components.get(Integer.valueOf(row));
        if (temp == null)
          temp = new JDateChooser();
          this.components.put(Integer.valueOf(row), temp);
        temp.setDate((Date) value);
        return temp;
      @Override
      public final void addCellEditorListener(final CellEditorListener arg0)
        this.listeners.addElement(arg0);
      @Override
      public final void removeCellEditorListener(final CellEditorListener arg0)
        this.listeners.removeElement(arg0);
      @Override
      public final void cancelCellEditing()
        return;
      @Override
      public final Object getCellEditorValue()
        return null;
      @Override
      public final boolean isCellEditable(final EventObject arg0)
        return true;
      @Override
      public final boolean shouldSelectCell(final EventObject arg0)
        return true;
      @Override
      public final boolean stopCellEditing()
        return true;
    }

    This seems to work:
    import java.awt.Component;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import java.sql.Date;
    import java.util.EventObject;
    import java.util.HashMap;
    import java.util.Vector;
    import javax.swing.JTable;
    import javax.swing.event.CellEditorListener;
    import javax.swing.event.ChangeEvent;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    import com.toedter.calendar.JDateChooser;
    public class DateCellEditor implements TableCellRenderer, TableCellEditor, PropertyChangeListener
      private static final long serialVersionUID = -5073758499524392257L;
      private final Vector<CellEditorListener> listeners = new Vector<CellEditorListener>();
      // oops.. lingering objects problem when rows are deleted..
      private final HashMap<Integer, JDateChooser> components = new HashMap<Integer, JDateChooser>();
      private Date storedValue = null;
      @Override
      public final Component getTableCellRendererComponent(final JTable table,
          final Object value, final boolean isSelected, final boolean hasFocus,
          final int row, final int col)
        JDateChooser temp = this.components.get(Integer.valueOf(row));
        if (temp == null)
          temp = new JDateChooser();
          temp.addPropertyChangeListener("date", this);
          this.components.put(Integer.valueOf(row), temp);
        temp.setDate((Date) value);
        return temp;
      @Override
      public final Component getTableCellEditorComponent(final JTable table,
          final Object value, final boolean isSelected, final int row,
          final int column)
        JDateChooser temp = this.components.get(Integer.valueOf(row));
        if (temp == null)
          temp = new JDateChooser();
          temp.addPropertyChangeListener("date", this);
          this.components.put(Integer.valueOf(row), temp);
        temp.setDate((Date) value);
        return temp;
      @Override
      public final void addCellEditorListener(final CellEditorListener arg0)
        this.listeners.addElement(arg0);
      @Override
      public final void removeCellEditorListener(final CellEditorListener arg0)
        this.listeners.removeElement(arg0);
      @Override
      public final void cancelCellEditing()
        return;
      @Override
      public final Object getCellEditorValue()
        return this.storedValue;
      @Override
      public final boolean isCellEditable(final EventObject arg0)
        return true;
      @Override
      public final boolean shouldSelectCell(final EventObject arg0)
        return true;
      @Override
      public final boolean stopCellEditing()
        return true;
      @Override
      public final void propertyChange(final PropertyChangeEvent arg0)
        if (((JDateChooser) arg0.getSource()).getDate() == null)
          return;
        this.storedValue = new Date(((JDateChooser) arg0.getSource()).getDate().getTime());
        ChangeEvent event = new ChangeEvent(arg0.getSource());
        for (int i = 0; i < this.listeners.size(); i++)
          this.listeners.elementAt(i).editingStopped(event);
    }

  • JTable: Custom cell renderer on T(row, col)

    Sorry if this was posted before, but the whole Search function doesn't seem to work these days (hasn't been working for a week now). Anyways:
    I know how to create custom cell renderers. My problem lies with which cells I want to apply that cell renderer to. It seems I am limited in setting a cell renderer to a whole column, which I don't want.
    For instance, I'd like to apply cell renderer R1 to (0,0) but not to (1,0) and not to (3,0). Instead I want cell renderer R2 on (2,0) and (3,0).
    Example of my table:
    |--icon--|--filename--|--extension--|
    |   R1   |  file1.txt |     txt     |
    |   R2   |  img1.jpg  |     jpg     |
    |   R1   |  file2.txt |     txt     |
    |   R2   |  img2.jpg  |     jpg     |
    |-----------------------------------|Is there any possibility this can be achieved? I am probably overlooking some method or class, but I don't know which. Some pointers or clues in the right directions are appreciated.
    Thanks

    Camickr, again you've been a great help. Works great, but a NullPointerException is being thrown and I can't find out what points to a null object.
    Code is this:
        public TableCellRenderer getCellRenderer(int row, int column) {
            if (getValueAt(row, 3).equals("jpg") && column == 0) {
                return new IconCellRenderer(Klue.iconAdd);
            } else {
                return super.getCellRenderer(row, column);
        }Solution is catching the NullPointerException in this method, but I'd rather have an if statement checking for it. But what to check? Any ideas?

  • 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

  • JTable Custom Cell  Event handling

    Hi,
    I have a column in JTable as image which is rendered by using custom cell renderer. I want to handle action event for the cell...
    I tried adding actionPerformed event for the button using which the image is rendered but the event is not triggered....
    Can you please tell me how to proceed with this
    Thanks,
    S.Anand

    I'm assuming you want to know when the user has clicked on a particular cell in the table. If so, add a MouseListener to the table then implement a MouseListener or one of the Mouse...Adapter classes with the method:
    public void mouseClicked(MouseEvent e)
        Point p = e.getPoint();
        int row = table.rowAtPoint(p);
        int col = table.columnAtPoint(p);
        // now do something according to the cell that was clicked

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

  • 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

  • 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

  • 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

  • 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

  • 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

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

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

Maybe you are looking for

  • Need help in restoring WHOLE AddressBook

    When I bought my iPad 2, iTune asked if I wanted to restore from my iPad 1 archive. (iPad 1 was deactivated and not connected to my account anymore.) I said yes.  AddressBook went crazy and started creating duplicate records for each entry. when I as

  • Range component in custom item renderer

    Hi, I am trying to put a spark Range component into the labelItemRenderer for flex mobile. Everytime I add it I get the error: "Skin for (long directory name for my range component) cannot be found". The custom item renderer is an actionscipt class b

  • How do I delete apps on iCloud?

    I want to erase the apps from iCloud.

  • Byte Corseca BT Stereo bluetooth Headset Not working in windows 8.1

    Hi I m using Byte Corseca BT Stereo bluetooth Headset its working fine in windows 8 . when i get update from microsoft windows 8.1 its not working ..Please any one give me the solution. Thanks in Advance Ramesh M

  • Computer freezes when trying to sync ipod touch

    I recently upgraded my laptop to Windows 7 64 bit and I'm not sure if I had this problem. I have the 64 bit version of itunes downloaded and I got a new 32gb ipod touch for christmas today. I plugged it in and set it all up and when it goes to sync,