1 2 Previous Next 16 Replies Latest reply on Jul 4, 2008 10:07 AM by kleopatra-JavaNet

    JTable-Row color issue

    701922
      Hi !

      I have JTable... with its 5columns,
      5th column is off Boolean Type.(check boxes)
      What I require.. is when user checks the JCheckbox.. I want that entire row to change its color and when un-checked reture back to its orginal color.

      I use DefaultTableModel.

      Pls post a simple samplecode..Thanks in advance.

      Pls help !!

      Edited by: dashok.83 on Jun 30, 2008 2:15 AM
        • 1. Re: JTable-Row color issue
          PhHein
          [JTable tutorial about renderers|http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#renderer]
          • 2. Re: JTable-Row color issue
            camickr
            I would override the prepareRenderer() method of JTable instead of creating a custom renderer. I've posted an example in the forum.
            • 3. Re: JTable-Row color issue
              701922
              I got this from the other thread...
              public Component prepareRenderer(
              TableCellRenderer renderer, int row, int column)
                   {
                           Component c = super.prepareRenderer(renderer, row, column);
                         if (!isRowSelected(row))
                            {
                             String type = (String)getModel().getValueAt(row, 0);
                             c.setBackground(
                             "Buy".equals(type) ? Color.GREEN : Color.YELLOW );
                        }     
               
              //                    if (isRowSelected(row) && isColumnSelected(column))
              //                         ((JComponent)c).setBorder(new LineBorder(Color.red));
               
                                  return c;
                             }
              Can u tell .. is there a way to set the row color.. depending on the cell value.

              ie, my fifth column has JCheckboxs... if user checks them I want the row to be colored(any color) and if he un-checks... the color s'd be re-set to the original...

              pls help ... !!!

              Edited by: dashok.83 on Jun 30, 2008 9:14 PM
              • 4. Re: JTable-Row color issue
                843806
                getModel().getValueAt(row, 4);
                depending on the value of you can set color accordingly
                • 5. Re: JTable-Row color issue
                  701922
                  I try like this... But its not working...

                  It is setting color for all the rows above... the the row that is selected.

                  Moreover ... it is not checking for the cell value :-(


                  public Component prepareRenderer(
                                                TableCellRenderer renderer, int row, int column)
                                           {
                                                Component c = super.prepareRenderer(renderer, row, column);
                             
                                                /*if (!isRowSelected(row))
                                                {
                                                     String type = (String)getModel().getValueAt(row, 0);
                                                     c.setBackground(
                                                          "Buy".equals(type) ? Color.GREEN : Color.YELLOW );
                                                }*/
                                                
                                                //if (isRowSelected(row) && isColumnSelected(5))
                                                if (isRowSelected(row) || getModel().getValueAt(row, 5)==new Boolean(true))
                                                     //((JComponent)c).setBorder(new LineBorder(Color.red));
                                                     c.setBackground(Color.ORANGE);
                                                else if (getModel().getValueAt(row, 5)==new Boolean(false))
                                                     c.setBackground(Color.LIGHT_GRAY);
                                                return c;
                                           }
                  • 6. Re: JTable-Row color issue
                    darrylburke
                    It is setting color for all the rows above... the the row that is selected.
                    You have an if / else if structure with no default fallback. If both conditions evaluate to false, the color last set will carry over.

                    You also a lot of krap with new Boolean(...) in your test conditions which makes me think you have no business coding GUIs with custom features: you need to go back to basics and learn the Java language.

                    Maybe something like (tweak the colors to what you want to achieve)
                    if (isRowSelected(row) || getModel().getValueAt(row, 5)) {
                       c.setBackground(Color.ORANGE);
                    } else if (!getModel().getValueAt(row, 5)) {
                       c.setBackground(Color.LIGHT_GRAY);
                    } else {
                       c.setBackground(Color.GREEN);
                    }
                    For posting code, indent with 2 to 4 spaces, not tabs as the forum software doesn't handle tabs very well.

                    db
                    • 7. Re: JTable-Row color issue
                      701922
                      Thanks ! Darryl.

                      Yep..will learn the basics.
                      But tell me this...
                      below code does change the color.. but it is changing only when I click again on another CheckBox.
                      ie, To see teh color change I need to check/uncheck another checkBox
                      public Component prepareRenderer(
                        TableCellRenderer renderer, int row, int column)
                           {
                              Component c = super.prepareRenderer(renderer, row, column);
                              if (isRowSelected(row) || getModel().getValueAt(row, 5).equals(true)) {
                           c.setBackground(Color.ORANGE);
                              }
                              else if (getModel().getValueAt(row, 5).equals(false)) {
                                      c.setBackground(Color.LIGHT_GRAY);
                              } 
                              else{
                                     c.setBackground(Color..WHITE);
                               }
                      return c;
                      }
                      Edited by: dashok.83 on Jul 1, 2008 3:46 AM

                      Edited by: dashok.83 on Jul 1, 2008 3:56 AM
                      • 8. Re: JTable-Row color issue
                        darrylburke
                        To get better help sooner, post a SSCCE that clearly demonstrates your problem.

                        And WTF are you testing .equals(true) and .equals(false) for?
                        if (something == true)
                        is the same as
                        if (something)
                        and
                        if (something == false)
                        is the same as
                        if (!something)
                        And using the equals method to compare a primitive return value to a primitive literal (both of which will probably be autoboxed) may or may not work as expected (I wouldn't even want to try) but makes for code that is painful to read and maintain.
                        db
                        • 9. Re: JTable-Row color issue
                          701922
                          hey,

                          WILL TALK ABOUT THAT LATER....

                          Can address to my question... ???
                          • 10. Re: JTable-Row color issue
                            camickr
                            Can address to my question... ???
                            Your question was addressed. The answer was to post a SSCCE so we can see exactly what is happening.
                            • 11. Re: JTable-Row color issue
                              701922
                              import java.awt.Color;
                              import java.awt.Component;
                              import java.awt.event.MouseEvent;
                              
                              import javax.swing.*;
                              import javax.swing.event.*;
                              import javax.swing.table.AbstractTableModel;
                              import javax.swing.table.DefaultTableCellRenderer;
                              import javax.swing.table.DefaultTableModel;
                              import javax.swing.table.TableCellEditor;
                              import javax.swing.table.TableCellRenderer;
                              import javax.swing.table.TableColumn;
                              import javax.swing.table.TableColumnModel;
                              import javax.swing.table.TableModel;
                              
                              public class test extends JFrame
                              {
                              
                                      JTable view_table;
                                      JScrollPane view_tpane;
                                   
                                      private String[] columnNames = {"COMP",
                                          "FILE NAME",
                                          "FILE LOCATION",
                                          "HOT #",
                                          "APPLIED ON",
                                          "DELETE"};
                                   
                                      private Object [][] data = {{ "XYZ","aaaa","wwww","wwsws","july",new Boolean(false)},
                                   { "XYZ","aaaa","wwww","wwsws","july",new Boolean(false)},
                                   { "XYZ","aaaa","wwww","wwsws","july",new Boolean(false)},
                                   { "XYZ","aaaa","wwww","wwsws","july",new Boolean(false)},
                                   { "XYZ","aaaa","wwww","wwsws","july",new Boolean(false)},
                                   { "XYZ","aaaa","wwww","wwsws","july",new Boolean(false)}
                                   };
                                   
                              Object [] rowData;
                              Class types[]=new Class[]{ String.class,String.class,String.class,String.class,String.class,Boolean.class};
                              DefaultTableModel viewModel;
                              JPanel panel;
                              JFrame frame ;
                                   
                              test()
                              
                              {
                                             
                               panel = new JPanel();
                              
                                viewModel=new DefaultTableModel(data,columnNames);
                                          
                                view_table = new JTable(viewModel){
                                public Class getColumnClass(int c){
                                         return types[c];
                                }       
                                public String getToolTipText( MouseEvent e )
                                {
                                              int row = rowAtPoint( e.getPoint() );
                                   int column = columnAtPoint( e.getPoint() );
                                   Object value = getValueAt(row, column);
                                   return value == null ? null : value.toString();
                              }
                              public boolean isCellEditable(int r, int c) 
                              {
                                    if(c == 5) 
                                     return true; 
                                    else
                                      return false ;
                               }
                                public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
                                   {
                                                 Component c = super.prepareRenderer(renderer, row, column);
                                      Boolean b= (Boolean) getModel().getValueAt(row, 5);
                                      if (b)
                                         c.setBackground(Color.ORANGE);
                                      else if (!b)
                                         c.setBackground(Color.LIGHT_GRAY);
                                      else 
                                         c.setBackground(Color.WHITE);
                                      return c;
                                   }
                              
                                     };
                                         this.setSize(500, 500);
                                          
                                        view_tpane=new JScrollPane(view_table);
                                        view_table.revalidate ();
                                        view_tpane.setBounds(60,100,750,175);
                                        view_table.setRowHeight(20);
                                        view_table.setBackground(Color.lightGray);
                                        panel.add(view_tpane);
                                        this.add(panel);
                                        this.show();
                                   
                                        
                                   }
                                   public static void main(String a[])
                                   {
                                        
                                        new test();
                                        
                                   }
                                   
                              }
                              What I need is ..when I check the last column... that entire row s'd change color and when I un-check row color s'd be come back to its orginal color.

                              S'd I be using... "TableModelListner"... ???
                              • 12. Re: JTable-Row color issue
                                darrylburke
                                You need to tell the table to repaint itself whenever the checkbox is (un)checked. Some other comments:
                                -- Your class uses a JFrame, it is not a specail type of JFrame. Favor composition over inheritance.
                                -- Your boolean conditions in the prepareRenderer are still messed up. When will the second else ever be entered? considering that you test if(b)...else if(!b).
                                -- Unnecessary complication in an SSCCE like including tooltip logic which is not relevant here. Nor is it necessary to house the scroll pane in a panel for a SSCCE that shows your problem.
                                -- Highly inconsistent indentation with a mixture of tabs and spaces and even trailing tabs and spaces. For posting on this forum, it is better to use 2 to 4 spaces, not tabs as the forum software doesn't handle tabs too well.
                                -- Braces for if/else blocks and spaces after commas don't cost money. Use them. It makes the code much more readable and less prone to mistakes during maintenance. And adopt a consistent bracing style.
                                -- Swing GUIs should always be launched on the EDT.
                                import java.awt.Color;
                                import java.awt.Component;
                                import java.awt.event.*;
                                import javax.swing.*;
                                import javax.swing.table.*;
                                
                                public class RowColor {
                                   JTable view_table;
                                   
                                   private String[] columnNames = {
                                         "COMP",
                                         "FILE NAME",
                                         "FILE LOCATION",
                                         "HOT #",
                                         "APPLIED ON",
                                         "DELETE"
                                   };
                                   
                                   private Object[][] data = {
                                         {"XYZ", "aaaa", "wwww", "wwsws", "july", new Boolean(false)},
                                         {"XYZ", "aaaa", "wwww", "wwsws", "july", new Boolean(false)},
                                         {"XYZ", "aaaa", "wwww", "wwsws", "july", new Boolean(false)},
                                         {"XYZ", "aaaa", "wwww", "wwsws", "july", new Boolean(false)},
                                         {"XYZ", "aaaa", "wwww", "wwsws", "july", new Boolean(false)},
                                         {"XYZ", "aaaa", "wwww", "wwsws", "july", new Boolean(false)}
                                   };
                                   
                                   Class[] types=new Class[] {
                                         String.class, String.class, String.class,
                                         String.class, String.class, Boolean.class
                                   };
                                   
                                   void makeUI() {
                                      DefaultTableModel view_Model = new DefaultTableModel(data,columnNames);
                                      
                                      view_table = new JTable(view_Model) {
                                         public Class getColumnClass(int c) {
                                            return types[c];
                                         }
                                         
                                         public boolean isCellEditable(int r, int c) {
                                            return c == 5;
                                         }
                                         
                                         public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
                                            Component c = super.prepareRenderer(renderer, row, column);
                                            Boolean b= (Boolean) getModel().getValueAt(row, 5);
                                            c.setBackground(b ? Color.ORANGE : Color.LIGHT_GRAY);
                                            return c;
                                         }
                                         
                                         public Component prepareEditor(TableCellEditor editor, int row, int column) {
                                            Component c = super.prepareEditor(editor, row, column);
                                            if (column == 5) {
                                               JCheckBox check = (JCheckBox) c;
                                               check.addActionListener(new ActionListener() {
                                                  public void actionPerformed(ActionEvent e) {
                                                     view_table.repaint();
                                                  }
                                               });
                                            }
                                            return c;
                                         }
                                      };
                                      
                                      view_table.setBackground(Color.lightGray);
                                      JScrollPane view_tpane=new JScrollPane(view_table);
                                      
                                      JFrame frame = new JFrame("Row Color");
                                      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                                      frame.setSize(500, 500);
                                      frame.setLocationRelativeTo(null);
                                      frame.add(view_tpane);
                                      frame.setVisible(true);
                                      
                                   }
                                   
                                   public static void main(String a[]) {
                                      SwingUtilities.invokeLater(new Runnable() {
                                         public void run() {
                                            new RowColor().makeUI();
                                         }
                                      });
                                   }
                                }
                                db

                                edit
                                -- use of deprecated method show() instead of the recommended setVisible(true)

                                Edited by: Darryl.Burke
                                • 13. Re: JTable-Row color issue
                                  701922
                                  Thank you so much. !

                                  I really value ur suggestions.

                                  I'm new to this forum.. but that can't be a excuse.

                                  Will follow ur tips/suggestion from my next post.
                                  • 14. Re: JTable-Row color issue
                                    camickr
                                    public Component prepareEditor(TableCellEditor editor, int row, int column) {
                                                Component c = super.prepareEditor(editor, row, column);
                                                if (column == 5) {
                                                   JCheckBox check = (JCheckBox) c;
                                                   check.addActionListener(new ActionListener() {
                                                      public void actionPerformed(ActionEvent e) {
                                                         view_table.repaint();
                                                      }
                                                   });
                                                }
                                                return c;
                                             }
                                    The editor is shared between all cells so I would guess that a new ActionListener is added to the check box every time you click on the cell. Which means multiple repaint requests are being generated as you keep clicking on the check boxes.

                                    I would try overriding the stopEditing() method to control the repainting. You can get the currently selected row and repaint only that row.

                                    Or, as you suggested you could use a TableModelListener to control repainting the row when the value is changed.
                                    1 2 Previous Next