Custom Cell Renderer issue in Custom JTable

I have CustomeTable extends JTable which renders different UI Components like (JTextField/ ComboBox /JButton/JCheckBox) in *"single column*" so i have overridden *getCellRenderer* and *getCellEditor methods.*
Now my Custom Table changes contextually by selecting different nodes in JTree similar to Windows Explorer
*The problem is Some times When i Click Button & then i click other Node which displays other UIComponents old components (Button is painted) instead of new COmponent(JTextfield or ...)*
*For each UI Renderer i have called its repaint() method still this issue is noticed not frequentlly but yes occasionally.*

Following are some of my Custom Text / Combo Renderer / Password / Button to display different UI Components @ Column 2 as per my above Code
private class MyDefaultRenderer implements TableCellRenderer {
        private JTextField l;
        private Border borderPrevious;
        public MyDefaultRenderer() {
            l = new JTextField();
            borderPrevious = l.getBorder();
        public Component getTableCellRendererComponent(JTable table,
                Object value,
                boolean isSelected,
                boolean hasFocus,
                int row,
                int column) {
            PropertyInfoType propertyType = propertyInfoList.get(row).getType();
            if (ConfigCommonPropertyPanel.isInputEditable && !propertyInfoList.get(row).isReadOnly()) {
            String tempVal = "";
            if (value != null && value instanceof String) {
                tempVal = value.toString();
            l.setText(tempVal);
            l.setOpaque(true);
            l.revalidate();
            l.repaint();
            return l;
        public Object getCellEditorValue() {
            return l.getText();
       private class ButtonRenderer implements TableCellRenderer {
        JPanel buttonPanel;
        JButton button;
        public ButtonRenderer() {
            buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
            button = new JButton(getAdminUIMsg(168));
            buttonPanel.setOpaque(true);
            buttonPanel.add(button);
     public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            button.setFont(LNFManager.getThemeForComponent(table).getBodyText());
            buttonPanel.setPreferredSize(new Dimension(getPreferredSize().width, getRowHeight()));
            buttonPanel.revalidate();
            buttonPanel.repaint();
            return buttonPanel;
    private class ButtonEditor extends JButton implements TableCellEditor, ActionListener {
        int rowIndex;
        int columnIndex;
        JTable table;
        JPanel panel;
        public ButtonEditor() {
            super("Validate Database");
            panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
            addActionListener(this);
        public Component getTableCellEditorComponent(JTable table, Object value,
                boolean isSelected, int row, int column) {
            rowIndex = row;
            columnIndex = column;
            setOpaque(true);
            panel.setOpaque(true);
            panel.setPreferredSize(new Dimension(getPreferredSize().width, getRowHeight()));
            setFocusable(true);
            panel.repaint();
            panel.add(this);
            return panel;
        public Object getCellEditorValue() {
            return this.isSelected();
        public boolean isCellEditable(EventObject anEvent) {
            return true;
        public boolean shouldSelectCell(EventObject anEvent) {
            return true;
        public boolean stopCellEditing() {
            return true;
        public void cancelCellEditing() {
        public void addCellEditorListener(CellEditorListener l) {
        public void removeCellEditorListener(CellEditorListener l) {
        public void actionPerformed(ActionEvent e) {
                          try{
// Some Business Logic To check my Database / LDAP Connections on Button Click
                             }catch( Exception ex){
                              } finally{
                                        stopCellEditing();
                                        transferFocus();
               +Shouldnt i call repaint() on a specific Component for a Specific renderer ?+
My Code works perfectly 99 % of the times ..
But very rarely when i click My Button On my Custom Table say
When i click NODE A - which displays different UI in Right Split Info
Row 2 Column 2 - has Validate Button
Then i Click NODe B - Which displayes Contextual UI Components
Row 2 Column 2 should display TextBox (as expected)
but due to some rendering issue its Displaying same Validate Button
I have debugged and verified my logic to call renderer is perfect.
My rest of rows /columns displays appropriate UI Components except the
position of Button .
I think after my Button Editor is Invoked & i perform some business logic Button renderer is not getting invoked ???

Similar Messages

  • Cell rendering the JRadioButton in JTable(Most Urgent)

    Hai guys,
    How can I rendering the JRadioButton in JTable ?
    In JTable JCombo,JTexrField,JTextArea to be rendered.But I can't rendering the JRadioButton.
    This is urgent for me.
    By kavi...

    http://onesearch.sun.com/search/onesearch/index.jsp?qt=JRadioButton+in+JTable&qp=siteforumid%3Ajava57&chooseCat=allJava&col=developer-forums&site=dev

  • Custom table cell renderer in a JTable is not called

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

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

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

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

  • JFormattedTextField as custom cell renderer in JTable?

    I have my custom renderers in my custom JTable that work quite good so far. After upgrading to JDK 1.4, i want to finally use formatted text fields in my JTable. So, i extended my renderes to also support formatters. But this doesn't seem to work. The formatter of my DateRenderer's constructor is used. When i try to change it via my JTable's custom method
         * Set formatter for a column. The formatter is only used if a corresponding renderer is set up (see configColumn()).
         * @param columnIndex Index of colum (0 = first column).
         * @param formatter Formatter to set.
         * @return TableColumn object for given index or null.
        public TableColumn setFormatter(int columnIndex, AbstractFormatter formatter) {
            TableColumn result = null;
            if (columnIndex >= 0 && columnIndex < getColumnCount()) {
                result = getColumnModel().getColumn(columnIndex);
                TableCellRenderer tcr = result.getCellRenderer();
                if (tcr instanceof DateRenderer) {
                    DateRenderer dr = (DateRenderer) tcr;
    System.out.println("setFormatter("+columnIndex+","+formatter+")...");
                    dr.setFormatter(formatter);
                }//else: todo
            }//else: columnIndex invalid
            return result;
        }//setFormatter()that has a different formatter, it is not changed!

    Instead of using setFormatter(), i wrote my own set method:
         * Set DateFormat.
         * @param format DateFormat to set.
        public void setFormat(DateFormat format) {
            setFormatterFactory(new DefaultFormatterFactory(new DateFormatter(format)));
        }//setFormat()

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

  • 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 table model, table sorter, and cell renderer to use hidden columns

    Hello,
    I'm having a hard time figuring out the best way to go about this. I currently have a JTable with an custom table model to make the cells immutable. Furthermore, I have a "hidden" column in the table model so that I can access the items selected from a database by their recid, and then another hidden column that keeps track of the appropriate color for a custom cell renderer.
    Subject -- Sender -- Date hidden rec id color
    Hello Pete Jan 15, 2003 2900 blue
    Basically, when a row is selected, it grabs the record id from the hidden column. This essentially allows me to have a data[][] object independent of the one that is used to display the JTable. Instinctively, this does not seem right, but I don't know how else to do it. I know that the DefaultTableModel uses a Vector even when it's constructed with an array and I've read elsewhere that it's not a good idea to do what I'm trying to do.
    The other complication is that I have a table sorter as well. So, when it sorts the objects in the table, I have it recreate the data array and then set the data array of the ImmutableTableModel when it has rearranged all of the items in the array.
    On top of this, I have a custom cell renderer as well. This checks yet another hidden field and displays the row accordingly. So, not only does the table sort need to inform the table model of a change in the data structure, but also the cell renderer.
    Is there a better way to keep the data in sync between all of these?

    To the OP, having hidden columns is just fine, I do that all the time.. Nothing says you have to display ALL the info you have..
    Now, the column appears to be sorting properly
    whenever a new row is added. However, when I attempt
    to remove the selected row, it now removes a seemingly
    random row and I am left with an unselectable blank
    line in my JTable.I have a class that uses an int[] to index the data.. The table model displays rows in order of the index, not the actual order of the data (in my case a Vector of Object[]'s).. Saves a lotta work when sorting..
    If you're using a similar indexing scheme: If you're deleting a row, you have to delete the data in the vector at the INDEX table.getSelectedRow(), not the actual data contained at
    vector.elementAt(table.getSelectedRow()). This would account for a seemingly 'random' row getting deleted, instead of the row you intend.
    Because the row is unselectable, it sounds like you have a null in your model where you should have a row of data.. When you do
    vector.removeElementAt(int), the Vector class packs itself. An array does not. If you have an array, when you delete the row you must make sure you dont have that gap.. Make a new array of
    (old array length-1), populate it, and give it back to your model.. Using Vectors makes this automatic.
    Also, you must make sure your model knows the data changed:
    model.fireTableDataChanged(); otherwise it has no idea anything happened..
    IDK if that's how you're doing it, but it sounds remarkably similar to what I went thru when I put all this together..

  • 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

  • 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

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

Maybe you are looking for

  • Did something change for laptop-mode-tools last time?

    Hi, when I start laptop-mode daemon, I always get the following errors in my everything.log Jul 8 14:45:46 archbox laptop-mode: Considering /dev/sda. Jul 8 14:45:46 archbox laptop-mode: /dev/sda5 not found in PARTITIONS. Jul 8 14:45:46 archbox laptop

  • Language setting issue with Xcelsius 2008 - Web Service NW BI

    French language is set during Xcelsius installation. In Xcelsius, English is always set as the preference language. With Web Service NW BI, I get text data returned in French. English is also defined as  default language in SAP BW BI . I would like t

  • Link Airport Express to an AirPort Time Capsule to use Airplay?

    I am thinking about getting an 2GB AirPort Time Capsule. I use the Airplay feature on my Airport Express that is not part of the AirPort Time Capsule and that is the only reason I have not replaced the Airport Express with the Airport Time Capsule. H

  • Display all database results with URL variable?

    Hi, I am using PHP MySQL I have a database that is Alphabetically ordered. I am trying to create a dynamic page that will only show A, B, C, ... and so on. I do this by Creating links named after the letters in the Alphabet. I have a recordset that f

  • Pre-sale questions?

    Hi, since it seems impossible to contact Adobe in any way to get information BEFORE buying a product... I need to know whether Premiere Elements 8 allows you to add subtitles to your movies? I mean REAL subtitles that the user can enable or disable.