Setting row color in JTable

I am trying to display some rows in a JTable in a different color regardless of selection status. The row color criteria would be from data from the object in the row, i.e., given a certain status of a record, I would want to show it as red instead of black.

A few optimizations:
class StatusColorRenderer
extends DefaultTableCellRenderer
    public StatusColorRenderer()
        // super(); not needed, call by default
        setOpaque(true);
        // DefaultTableCellRenderer returns itself as a CellRenderer Component, it extends JLabel so you can call setOpaque on it
// since this method is called at every paint for every cell it should be HIGHLY optimized
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    Component c = super.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, column);
    MyObjectClass myObject  = ( MyObjectClass ) myTableModel.getMyVector().elementAt(row);
    <SomeClass> myStatus = myObject.getTheStatus();
    if ( myStatus.compareTo(Status.BAD_STAT) == 0)
        c.setForeground(Color.red);
    else if (myStatus.compareTo(Status.IN_PROGRESS) == 0)
        c.setForeground(Color.green);
    else if ( myObject.getOtherFactor().compareTo(OtherFactors.NOT_DEFAULT) ==  0)
        c.setForeground(Color.blue);
    else
        c.setForeground(Color.black);
    // c.repaint(); NEVER DO THAT
    return c;
StatusColorRenderer myRenderer = new StatusColorRenderer();
// only one instance of the renderer
for ( int i = myTableModel.getColumnCount() - 1 ; i >= 0 ; i-- )
   //column = myTable.getColumnModel().getColumn( i );
   myTable.setDefaultRenderer( myTable.getColumnClass( i ),
                                            myRenderer );
}Comment:
AbstractTableModel and DefaultTableModel.getColumnClass method returns Object.class, it is used by the JTable to setup the editor and the renderer of a column
so if you're using the DefaultTableModel and JTable without overriden getColumnClass, you can set a generic renderer for your JTable by using:
myTable.setDefaultRenderer( Object.class, myRenderer );

Similar Messages

  • Setting Row Color of the JTable

    Hi,
    I wanted to set the first row and first column of the JTable .
    Can anybody help me in this? I read CellRendering but didn't understood when getTableCellRendererComponent(...) method get called and how it works.
    I realy appreciate if anybody explains me.
    Thanks,
    Padmashree

    Hi,
    If my understading is correct, You are trying to set the color of the first column of the first row.
    "Renderer" returns the component used for drawing the cell. It applies for all the cell. Method called
    "GetTableCellRendererComponent" is used to configure the renderer appropriately before drawing.
    So the following parameters are provided to acheive it.
    table - the JTable that is asking the renderer to draw; can be null
    value - the value of the cell to be rendered.
    isSelected - true if the cell is to be rendered with the selection highlighted; otherwise false
    hasFocus - if true, render cell appropriately.
    row - the row index of the cell being drawn.
    column - the column index of the cell being drawn
    So to acheive your requrement, you have to do something like this.
    1 - apply the required color to first cell of the first row
    2 - configure in such a way that it works when the renderer reads first row and first column.
    For. e.g To set the background color as Blue,
         if(row == 0) && ( column == 0){
         this.setBackground(Color.Blue);                          }else {
              this.setBackground(defaultColor);
    Hope it gives a good picture.

  • Setting row color in REUSE_ALV_GRID_DISPLAY_LVC

    Hi,
    I'm not sure if this function perhaps is not released or has bugs?  I didn't see any OSS notes.  I've read several sources on how to set the color for a given line and I'm not sure why I don't see it.  I see the values in my internal table in the ROWCOLOR column.
    We are on 4.6C and I wanted to use the LVC function to move toward the ECC versions of the structures ( LVCS_LAYO instead of SLIS_S_LAYOUT).  Perhaps this function module is not really supported???
    Could the ZEBRA parameter throw it off?
    Could it be a buffer issue?  I've tried it alternate ways and don't see a difference.
    Thanks for any suggestions,
    Ray
    Here is the code I'm using to set the layout and define the table.:
    gs_alv-callback_pf_status    = 'PF_STATUS_SET'.
      gs_alv-callback_user_command = 'USER_COMMAND'.
      gs_alv-callback_program      = sy-repid.
      gs_alv-structure_name        = 'ZHUS_ST_SP_REPORT'.
      gs_alv-itabname              = 'GT_DATA'.
      gs_alv-itabwaname            = 'GS_DATA'.
      gs_layo-zebra                = 'X'.
      gs_layo-cwidth_opt           = 'X'.
      gs_layo-box_fname            = 'SELECTED'.  " Checkbox
      gs_layo-info_fname           = 'ROWCOLOR'.
      gs_layo-sel_mode             = 'B'. "Default - multiple rows
      CALL FUNCTION 'LVC_FIELDCATALOG_MERGE'
        EXPORTING
          i_structure_name             = gs_alv-structure_name
        CHANGING
          ct_fieldcat                  = gt_fcat.
    I set the color in my list table:
    ls_data-rowcolor = 'C600'.
          APPEND ls_data TO gt_data.
    This is how I call the grid:
    CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY_LVC'
        EXPORTING
          i_buffer_active                   = 'X'
          i_callback_program                = gs_alv-callback_program
          i_callback_pf_status_set          = gs_alv-callback_pf_status
          i_callback_user_command           = gs_alv-callback_user_command
          i_structure_name                  = gs_alv-structure_name
          i_grid_title                      = gs_alv-grid_title
          i_grid_settings                   = gs_glay
          is_layout_lvc                     = gs_layo
          it_fieldcat_lvc                   = gt_fcat
          it_excluding                      = gt_excluding
          i_default                         = gs_alv-default
          i_save                            = gs_alv-save
          is_variant                        = gs_disvariant
          it_events                         = gt_event
          it_event_exit                     = gt_event_exit
          is_print_lvc                      = gs_prnt
        TABLES
          t_outtab                          = <gfs_t>
    Edited by: Raymond Mannion on Jun 30, 2009 8:09 PM
    Edited by: Raymond Mannion on Jun 30, 2009 8:10 PM

    THis should help you:
    Re: 'Reuse_alv_grid_display' : making a specific row bold
    [ALV] Text in color and bold

  • Alternating row colors in JTable

    hi everybody,
    Can anyone tell me how i can change the colour of every other row in my JTable?
    Thanks
    Ivor

    Yes,
    using a TableCellRenderer. look at:
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#custom
    Phil

  • Changing Row Color In JTable !

    Hi friends
    I have two JTables. The first one has 7 columns and 10 rows (with data) but the second one is empty.
    The user can choose one row from first table and by pressing the ((copy)) button , copy that row to the second table. Is it possible to change the color of those rows(in the first table) that been copied to the second table. I mean if the user choose a row and copy then to the second table, the color of this row wold be changed.
    Can anybody help me with that??
    Thanks

    I think you are heading in the wrong direction here... you want to create a brand new DefaultTableCellRenderer and override the getTableCellRendererComponent method...
    public class MyRenderer extends DefaultTableCellRenderer {
      public Component getTableCellRendererComponent(JTable table, Object value,
                              boolean isSelected, boolean hasFocus, int row, int column) {
                  JLabel lbl = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus,
                               row, column);
                  //now I can change the background color depending on the row...
                  if (row == xxx) lbl.setBackground(Color.red);
    }Then use your new class on your table...
    <table.setDefaultRenderer(Object.class, new MyRenderer()); //the class must match what you TableModel returns for getColumnClass();Hope this helps,
    Josh Castagno
    http://www.jdc-software.com
    Hope this helps

  • Setting row count to JTable RunTime

    I am creating JTable at RuTime. I want to set the default 1 row for the Table
    df = new DefaultTableModel();
    jTable1.setModel(df);
    //add Columns to Table
    for(int i=0; i<chars.size(); i++)
    TableColumn col = new TableColumn();
    col.setHeaderValue(.....);
    col.setPreferredWidth(...);
    jTable1.addColumn(col);
    jTable1.updateUI();
    df.setRowCount(1); //Problematic code . if remove this line everithing works fine
    The above code does't work properly(the last line) Nothing displays on the screen and it's seems to doing processing in loop ...
    Plese provide the solution I reqires this urgently............

    what does "Problematic code" mean? Why can't people just post the error messag/exception? do you think we are prophets?

  • Set row height in JTable

    i would like to hide, show row/s in the JTable. I try it with setRowHeight but it affect all rows.
    is it possible to do it ? what shoud i rewrite(add) to create this functionality?
    i use JDK1.2.2 :-(
    thanks Tomas

    The other way is to modify your table model class:
    Let the getValueAt method return only the rows you need and the getRowsCount method return the needed row count.
    It may be done in respect to some condition of the table
    Best regards,
    Martin

  • How to set background color in row of JTable ?

    i am new in java please tell me about How to set background color in row of JTable ? please example code. Thnak you.

    Here is an example: http://www.javaworld.com/javaworld/javaqa/2001-09/03-qa-0928-jtable.html
    For more info on how to use tables read the swing tutorial: http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
    ICE

  • How do you set the font color for a specific entire row inside a JTable?

    How do you set the font color for a specific entire row inside a JTable?
    I want to change the font color for only a couple of rows inside a JTable.
    I've seen some ways to possibly do this with an individual cell.
    Clarification on changing the font color in an individual cell would be helpful too if
    there is no easy way to do this for a row.

    hai,
    Try out with this piece of code.Create your table and assign the renderer to each column in the table.
    CellColorRenderer m_CellColorRenderer = new CellColorRenderer();
    for(int i=0;i<your_JTable.getColumnCount();i++)
    your_JTable.getColumnModel().getColumn(i).setCellRenderer(m_CellColorRenderer);
    class CellColorRenderer extends JLabel implements TableCellRenderer
    CellColorRenderer()     
    setOpaque(true);     
    setHorizontalAlignment(LEFT);
    setVerticalAlignment(CENTER);
    setBackground(Color.white);
    setForeground(Color.black);
    protected void setValue(Object value)
         setText((value == null) ? "" : value.toString());
    public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected, boolean hasFocus, int row,int column)
         if(isSelected == true)
              setForeground(Color.red);
         else
              setForeground(Color.black);
         setValue(value);
         return this;
    regards,
    bala

  • Setting colors of the rows of  a JTable

    Hi,
    How can we set multiple colors(foreground) for multiple rows in a JTable?. (i want to set the color of the row depends on the value of a column. Foe example if the value of a particular column is "x" then i want to set the color of that particular row as "RED" or if the value of that column is "y" then i want to set the color of the column as "GREEN". )

    Try this:
    * Method to set custom cell renderer
    *Adopted from
    * http://javaalmanac.com/egs/javax.swing.table/Stripe.html
    JTable theTable = new JTable() {
    public Component prepareRenderer(TableCellRenderer renderer,
    int row, int col) {
    Component c = super.prepareRenderer(renderer, row, col);
    //Example assumes the column number is 1 and value is "Critical"
    if (theTable.getValueAt(row, 1) != null) {
    if (theTable.getValueAt(row, 1).equals("Critical")) {
    if (col == 1) {
    c.setForeground(Color.red);
    c.setBackground(new Color(255, 255, 204));
    c.setFont(new java.awt.Font("MS Sans Serif", 1, 11));
    return c;
    };

  • Changing background color in JTable, only changes one row at a time...

    I'm trying to change the color of rows when the 5th column meets certain criteria. I think I'm very close, but I've hit a wall.
    What's happening is the row will change color as intended when the text in the 5th column is "KEY WORD", but when I type "KEY WORD" in a different column it will set the first row back to the regular colors. I can easily see why it's doing this, everytime something is changed it rerenders every cell, and the listener only checks the cell that was just changed if it met the "KEY WORD" condition, so it sets every cell (including the previous row that still meets the condition) to the normal colors. I can't come up with a good approach to changing the color for ALL rows that meet the condition. Any help would be appreciated.
    In this part of the CellRenderer:
            if (isSelected)
                color = Color.red;
            else
                color = Color.blue;
            if (hasFocus)
                color = Color.yellow;
            //row that meets special conditions
            if(row == specRow && col == specCol)
                color = color.white; I was thinking an approach would be to set them to their current color except for the one that meets special conditions, but the two problems with that are I can't figure out how to getColor() from the table, and I'm not sure how I would initially set the colors.
    Here's the rest of the relevant code:
        public void tableChanged(TableModelEvent e)
            int firstRow = e.getFirstRow();
            int lastRow  = e.getLastRow();
            int colIndex = e.getColumn();
            if(colIndex == 4)
                String value = (String)centerTable.getValueAt(firstRow, colIndex);
                // check for our special selection criteria
                if(value.equals("KEY WORD"))
                    for(int j = 0; j < centerTable.getColumnCount(); j++)
                        CellRenderer renderer =
                            (CellRenderer)centerTable.getCellRenderer(firstRow, j);
                        renderer.setSpecialSelection(firstRow, j);
    import javax.swing.table.*;
    import javax.swing.*;
    import java.awt.Component;
    import java.awt.Color;
    public class CellRenderer extends DefaultTableCellRenderer
        int specRow, specCol;
        public CellRenderer()
            specRow = -1;
            specCol = -1;
        public Component getTableCellRendererComponent(JTable table,
                                                       Object value,
                                                       boolean isSelected,
                                                       boolean hasFocus,
                                                       int row, int col)
            setHorizontalAlignment(JLabel.CENTER);
            Color color = Color.green;
            if (isSelected)
                color = Color.red;
            else
                color = Color.blue;
            if (hasFocus)
                color = Color.yellow;
            if(row == specRow && col == specCol)
                color = color.white;
            //setForeground(color);
            setBackground(color);
            setText((String)value);
            return this;
        public void setSpecialSelection(int row, int col)
            specRow = row;
            specCol = col;
    }If I'm still stuck and more of my code is needed, I'll put together a smaller program that will isolate the problem tomorrow.

    That worked perfectly for what I was trying to do, but I've run into another problem. I'd like to change the row height when the conditions are met. What I discovered is that this creates an infinite loop since the resizing triggers the renderer, which resizes the row again, etc,. What would be the proper way to do this?
    Here's the modified code from the program given in the link. All I did was declare the table for the class, and modify the if so I could add the "table.setRowHeight(row, 30);" line.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    public class TableRowRenderingTip extends JPanel
        JTable table;
        public TableRowRenderingTip()
            Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
            Object[][] data =
                {"Buy", "IBM", new Integer(1000), new Double(80.5), Boolean.TRUE},
                {"Sell", "Dell", new Integer(2000), new Double(6.25), Boolean.FALSE},
                {"Short Sell", "Apple", new Integer(3000), new Double(7.35), Boolean.TRUE},
                {"Buy", "MicroSoft", new Integer(4000), new Double(27.50), Boolean.FALSE},
                {"Short Sell", "Cisco", new Integer(5000), new Double(20), Boolean.TRUE}
            DefaultTableModel model = new DefaultTableModel(data, columnNames)
                public Class getColumnClass(int column)
                    return getValueAt(0, column).getClass();
            JTabbedPane tabbedPane = new JTabbedPane();
            tabbedPane.addTab("Alternating", createAlternating(model));
            tabbedPane.addTab("Border", createBorder(model));
            tabbedPane.addTab("Data", createData(model));
            add( tabbedPane );
        private JComponent createAlternating(DefaultTableModel model)
            JTable table = new JTable( model )
                public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
                    Component c = super.prepareRenderer(renderer, row, column);
                    //  Alternate row color
                    if (!isRowSelected(row))
                        c.setBackground(row % 2 == 0 ? getBackground() : Color.LIGHT_GRAY);
                    return c;
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            table.changeSelection(0, 0, false, false);
            return new JScrollPane( table );
        private JComponent createBorder(DefaultTableModel model)
            JTable table = new JTable( model )
                private Border outside = new MatteBorder(1, 0, 1, 0, Color.RED);
                private Border inside = new EmptyBorder(0, 1, 0, 1);
                private Border highlight = new CompoundBorder(outside, inside);
                public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
                    Component c = super.prepareRenderer(renderer, row, column);
                    JComponent jc = (JComponent)c;
                    // Add a border to the selected row
                    if (isRowSelected(row))
                        jc.setBorder( highlight );
                    return c;
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            table.changeSelection(0, 0, false, false);
            return new JScrollPane( table );
        public JComponent createData(DefaultTableModel model)
            table = new JTable( model )
                public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
                    Component c = super.prepareRenderer(renderer, row, column);
                    //  Color row based on a cell value
                    if (!isRowSelected(row))
                        c.setBackground(getBackground());
                        String type = (String)getModel().getValueAt(row, 0);
                        if ("Buy".equals(type)) {
                            table.setRowHeight(row, 30);
                            c.setBackground(Color.GREEN);
                        if ("Sell".equals(type)) c.setBackground(Color.YELLOW);
                    return c;
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            table.changeSelection(0, 0, false, false);
            return new JScrollPane( table );
        public static void main(String[] args)
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
        public static void createAndShowGUI()
            JFrame.setDefaultLookAndFeelDecorated(true);
            JFrame frame = new JFrame("Table Row Rendering");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add( new TableRowRenderingTip() );
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
    }Edited by: scavok on Apr 26, 2010 6:43 PM

  • Work with JTable cell (check input, set text color)

    I have a JTable with data
    The task is:
    User inputs some data into cell
    I want to check his input string for equatily with other values in column
    For example, I have these values in column:
    1.example
    2.exercise
    3.execute
    User inputs word "execution" in the same column
    until user inputs "executi" his input string should be red.
    What event I have to listen to if I want to get user input string?
    Also a question:
    Is there any opportunity to work with cell row (copy it to another JTable) ?
    Message was edited by:
    Holod

    i think you should use cell editor as textfield (although that is default for jtable) and then implements document listener and set text color in insert update method.
    try this out :-)

  • Coloring row problem of JTable

    Hi!
    I'm the beginer and have a problem while coloring rows in my table. The problem is as follows:
    i need to color the whole row when i click a single cell of this row. Everything is ok until i click another cell of another row. When i do it all the row between first and last clicked become colored!
    I tryed manipulating table.setSelectionMode(i) - but nothing!
    My very simple code:
    DefaultTableCellRenderer renderer = new 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);
                    if (isSelected) {cell.setBackground(Color.LIGHT_GRAY);return cell;}
                    return cell;
    for(int i=0; i<table.getColumnCount(); i++)
                table.getColumnModel().getColumn(i).setCellRenderer(renderer);
    Please help!
    PS I cant use Ctrl button in my program because all the changes in table are in table.isEnable(false)-mode-it is the condition of my work.

    Karl already gave the correct answer: once you touched any Color property of a DefaultTableCellRenderer, you have to do it always, that is in any of the logic branches. That's because DTCR has a nasty color "memory" which basically is the net result of inapproriate subclassing (no compelling reason for a renderer to-be a component) and frozen api (couldn't add a setRendererXXColor) at the particular moment of evolution when it was needed. (Our SwingX wiki about swingx renderer/highlighter support has more details)
    BTW, if I interpret your code snippet correctly, you are after a different selection color for all columns? If so you can set that color globally for your table instance (hint: api doc is your friend :-), no need for a custom renderer.
    HTH
    Jeanette

  • HELP!! set the cell color in jTable

    I need to set the color of a specific cell in jTable, but, I need to retain the old color in the jTable. It must not reset the whole table.
    would anyone help me in this problem... PLSSSSS its urgent

    A flexible variation on this is to specify formatting options in the JTable's client properties:
    // Use some sort of special "key" to indicate the cell and that you want to set the background color
    String key = "background:" + row + "," + column;
    table.putClientProperty(key, Color.green);You can then write a general table cell renderer that looks for these special formatting options and it doesn't disrupt your existing TableModel in any way:
    public class FormattingTableCellRenderer extends DefaultTableCellRenderer
      public Component getTableCellRendererComponent(JTable table, Object value, int row, int column, ...)
        Component component = super.getTableCellRendererComponent(table, value, row, column, ...);
        // See if the JTable specifies any properties to override the default format
        Color backgroundColor = (Color)table.getClientProperty("background:" + row + "," + column);
        if(backgroundColor != null)
          component.setBackground(backgroundColor);
        return component;
    }Any custom cell renderers you have then simply need to extend FormatTableCellRenderer instead of DefaultTableCellRenderer.
    It's very easy to add formatting options other than background, such as font, to the list of recognised attributes. You'll probably need to make some alterations to get it to recognise selection/focus but hopefully you get the idea.
    Hope this helps.

  • Changing JTable Row Color OnMouseOver

    Hello everybody,
    is it possible to change JTable Row Color when Mouse passes over it ??
    THanks!

    Yes...
    You have to override the table cell renderer and set the color of the rows based on flag.
    The flag can be turned on/off in a mouse motion listener of the table.

Maybe you are looking for

  • Multiple clients on same account? Feature request...

    Hi, I suspect many or most users have a phone and a PC of some sort.  I have a Mac laptop and a Linux box and an Android phone. My problem is that I can only have one client signed in at a time.  If I'm on (for example) the Mac, then close the lid an

  • Problem in item category

    Hi .. Im facing an error while creating PO due to item category. 'B' i.e. l'imit'. When i checked the fields of item category B', i found that in IR indicator field in invocie control section , filed FIRM IN PO is ch.. i want checked.. i wnat to unch

  • Viewing a video

    Recently acquired an IMAC OS 9.2.2. Built in memory 64MB, Video memory 8MB. Virtual memory 124 MB used on MAC HD, largest unused block 96.2 MB. Built in 15 inch display(13.8 inch viewable). Complete novice regarding using computers, Problem is on try

  • How to replace Office Publisher?

    Happy new owner of the MacBook. Having produced a lot of stuff on my PC with Office 2003 Publisher - What program to choose for my Mac? I love the iWeb features and I have thought of buying the iWork set. Can anyone confirm if the iWork is compatible

  • Joining 2 Bex queries in Webi (BI 4.0)

    Hi, I have the following requirement. I want to join the results of 2 BEx queries in Webi (BI 4.0). I'm using the BICS connection, no universe. E.g. query 1: Country    Region          Amount Germany           EMEA           5 China                 A