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

Similar Messages

  • Edit Appraisals:  Notes only shows one row at a time

    Under the Employee Review tab of MSS-->Edit Appraisals, when I click to create an appraisal, the appraisal form in our system has areas to add notes.  However, in the portal, the area to add notes is only 1 row.  It is scrollable, but you can only see one row of text at a time.  How can I expand the notes area/editor to show multiple lines of text?

    Turns out the configuration is on the R/3 side when setting up the Appraisal.  There is an option for number of lines for notes.

  • My table lists only up one row at a time. dynamic don't work

    Hi!
    I have a table that consists of: ID, NAME, LINK and
    CONTENTID.
    It's 5 records in it at the moment.
    I create a recordset.
    I choose all (ID, NAME, LINK and CONTENTID).
    It only shows up ONE row. I mark the table and choose
    repeating behavior. I still only get up one row.
    I follow this tutorial:
    http://www.adobe.com/support/dreamweaver/building/users_delete_rcrds_php/users_delete_rcrd s_php03.html
    I use Dreamweaver CS3.
    Any good advice, cause I haven't got a clue.
    I've tried everything: the embassy, the German government,
    the consulate. I even talked to the U.N. ambassador. It's no use, I
    just can't bring my wife to orgasm.
    Marw

    Can't get it to work. But I start off with this:
    1.
    http://img521.imageshack.us/my.php?image=01tablexk1.png
    After I follow your instructions, and mark
    name I get this:
    http://img514.imageshack.us/my.php?image=02trselectedzg6.png
    But still I only get one post and have to use a Recordset
    navigation bar instead.
    Marw

  • How to change the particular column background  color in jTable?

    I am woking with a project, in which I am using a jTable. Then
    How to change the particular column background color in jTable?

    Use a custom Renderer. This is the JTable tutorial:
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html

  • How to change background color in online editor

    How to change background color in online editor

    Jeff,
    if you try to change all the plsql keywords to the same background color (that is not either white or black or blue) via the options panel in SQL Developer (Code Editor > PLSQL syntax colors), you will get the new background color in the worksheet only for the areas with plsql text, while the areas without any text will have the same background color as the base color scheme you started with. This means that there is no way to change the "general background" color via the options panel, but you have to use the same background color of one of the predefined color schemes.
    This seems to me a bug, but probably it's not considered high priority, so it will not be fixed for the time being.
    I would like to stress the fact that being able to change the color scheme of the development environment that you use every day about 8 hours a day can make quite a difference on your eyes at the end of the day.
    Thanks,
    Paolo

  • How to change background color of multilevel textbox in oracle form 6i

    hi
    How To Change background Color of the Text.
    In One Multilevel Block 10 Record is Display At a Time in a Text Box (Name is AMTt)
    This Text Box display , Buffer and Record Length is 10
    In Case Of Amount is Less 500 then Text Color Is Red(Or Any) and In Case Amount Is More 500 Then Color is Green (Or Any).
    Me Use This Code in PRE_RECORD EVENT
    TCMTL is Block name
    TCMTL_AMT is Text Box Name
    if :TCMTL.TCMTL_AMT >5000 then
         g_fun.msgbox('Values is more');
         Set_Item_Property('TCMTL_AMT' , BACKGROUND_COLOR, 'r50g100b100');
    else
         g_fun.msgbox('Values is Less');
         Set_Item_Property('TCMTL_AMT' , BACKGROUND_COLOR, 'r50g100b10');
    end if;     
    but This Code Is Refer Only 10th Value and change color depend on value.
    so
    possible to Different color in One Block Text Box Then how?

    DECLARE
         cur_itm VARCHAR2(80);
         cur_block VARCHAR2(80) := Name_in('system.trigger_block') ;
         BEGIN
         cur_itm := Get_Block_Property( cur_block, FIRST_ITEM );
    WHILE ( cur_itm IS NOT NULL ) LOOP
              cur_itm := cur_block||'.'||cur_itm;
              --:global.VISUAL_ATTRIBUTE:= 'BACKGROUND_COLOR';
              --:global.VISUAL_ATTRIBUTE:= get_item_property(cur_block||'.'||cur_itm ,Background_Color);
              IF :TCMTL.TCMTL_AMT >= 500 THEN
                             Set_Item_Instance_Property( cur_itm, CURRENT_RECORD, VISUAL_ATTRIBUTE,'r50g100b100');
                   ELSE
                             Set_Item_Instance_Property( cur_itm, CURRENT_RECORD, VISUAL_ATTRIBUTE,'r5g100b10');
                   END IF;
                             cur_itm := Get_Item_Property( cur_itm, NEXTITEM );
                   END LOOP;
                   next_record;
    END;
    this is my in that how to set a VISUAL_ATTRIBUTE, and where to set so get a background color of text and change

  • Hover over image will change background color and size since IE8

    Hello,
    I have a problem that only occurs in IE8 without compability view.
    I have in CSS set all textlinks to change background color on hover.
    Now my sliced imageslinks also change background color and for a larger background area than the actual image.
    It filles out the area outside the sliced image.
    This hasnt happened before in any other versions of IE and it looks fine in Firefox.
    Please can some one help me !
    I have been searching net for hours.
    I tried to change the background color when hovering imagelinks. Maybe I did something wrong but it didnt help.
    BR,
    Peter

    Noone that can give me a clue?
    I have been trying to figure this out all day

  • How to change background color in AutoComplete window ?

    Is it possible to change background color in AutoComplete window ?

    Bob, A.Ankit, you're both chasing a ghost here.
    The screenshot shows an autocomplete enabled textbox with its dropdown list of autocomplete values to choose from. There is no property defining its backcolor. Not in the textbox nor in any class, neither any other baseclass nor _combobox of _base.vcx
    The only way to chnage that color is not recommended, via changing windows theme colors. That would effect any window and control.
    If you need another color even turning off themes won't help as VFP doesn't offer any property controlling that color, so you really would need to implement the autocomplete feature yourself, if you want the specify this backcolor.
    Bye, Olaf.
    Olaf Doschke - TMN Systemberatung GmbH http://www.tmn-systemberatung.de

  • How to change background color of text in pdf based by font name

    Hi
    How to change the background color of text in PDF based by font name. Is there any option in Javascript. e.g: If PDF containing ARIAL font, the ARIAL text background color needs to be changed in red color for all pages. Same for all fonts with different different color in the PDF.
    Thanks in Advance

    Hi
    1) Is there any possibilities to highlight with different color based on font using javascript
    2) list of font used in PDF using javascript
    3) How to hilight the text using javascript
    Thanks in Advance

  • How to change background color in photoshop cs3

    how to change background color in photoshop cs3
    Please help me...

    Background for what? You need to explain better and be more specific.
    Mylenium

  • Pages 5 can't change background color in fullscreen

    There's no option to change background color when in fullscreen mode anymore.
    Did I miss something or did apple just...get rid of it?????why???

    Hi, Mark,
    Under the Format menu select Advanced and the click on Make Master Objects Selectable. Now click on the red area. You'll notice little faint x's at the corners. In the Arrange menu click on Unlock. Now you can edit the color. (In this case a gradient.) When you finish, go back and Lock it again and deselect Make Master Object Selectable.
    Walt

  • Change background color in enter-query mode

    Hi everyone,
    I am trying to Change background color in enter-query mode in forms10g. I am using this
    Set_Item_property('org.branch_code', BACKGROUND_COLOR, 'Green' );
    Thanks

    This is the code that allows to colorise items in enter_query mode, then de-colorize them after execute_query.
    Assume that you have created a VA_QUERY visual atribute in your module.
    -- Colorise in enter-query mode --
    PROCEDURE Start_query IS
      LC$Block      Varchar2(30) := Name_in('system.trigger_block') ;
      LC$item       varchar2(60);
      LC$itemdeb    varchar2(60);
      LN$len        pls_integer ;
    BEGIN
      lc$itemdeb := get_block_property(LC$BLOCK, FIRST_ITEM) ;
      lc$item := LC$BLOCK || '.' || lc$itemdeb ;
      while lc$itemdeb is not null Loop
        IF GET_ITEM_PROPERTY(LC$Item , ITEM_TYPE) NOT IN ('BUTTON','RADIO GROUP','DISPLAY ITEM') Then
          IF GET_ITEM_PROPERTY(LC$Item , QUERYABLE ) = 'TRUE' Then
            set_item_property(LC$item, CURRENT_RECORD_ATTRIBUTE, 'VA_QUERY');
          End if ;
        End if ;
        lc$itemdeb := get_item_property( lc$item, NEXT_NAVIGATION_ITEM );
        lc$item := LC$BLOCK || '.' || lc$itemdeb ;
      end loop ;
    END;
    -- Unclororize after execute_query --
    PROCEDURE End_query IS
      LC$Block     Varchar2(30) := Name_in('system.trigger_block') ;
      LC$item     varchar2(60);
      LC$itemdeb     varchar2(60);
      LN$len          pls_integer ;
      LN$Multi  pls_integer ;
    BEGIN
      lc$itemdeb := get_block_property(LC$BLOCK, FIRST_ITEM) ;
      lc$item := LC$BLOCK || '.' || lc$itemdeb ;
      LN$Multi := GET_BLOCK_PROPERTY(LC$Block , RECORDS_DISPLAYED ) ;
      while lc$itemdeb is not null Loop
        IF GET_ITEM_PROPERTY(LC$Item , ITEM_TYPE) NOT IN ('BUTTON','RADIO GROUP','DISPLAY ITEM') Then
          IF GET_ITEM_PROPERTY(LC$Item , QUERYABLE ) = 'TRUE' Then
             If LN$Multi > 1 Then
                set_item_property(LC$item, CURRENT_RECORD_ATTRIBUTE, 'VA_CURRENT_RECORD');
             Else
                set_item_property(LC$item, CURRENT_RECORD_ATTRIBUTE, '');
             End if ;
          End if ;
        End if ;
        lc$itemdeb := get_item_property( lc$item, NEXT_NAVIGATION_ITEM );
        lc$item := LC$BLOCK || '.' || lc$itemdeb ;
      end loop ;
    END;Francois

  • Change background color

    HI guys,
    I have a question:
    In the Form 6I exists a Text Item with own scrollbar.
    Are there any options to change background color on scrollbar attached to that item?
    Thanks in advance,
    John.
    Message was edited by:
    IMJL

    In the Form 6I exists a Text Item with own scrollbar.If you rae talking about text item, you can set property word yes and vertical scroll = yes
    For second question ,as Francois said, the answer is No

  • Change background color of textbox based on non-visible value

    Hello,
    I have a 10g master - detail form. I was wondering how can I change background color of text box (NAME) based on non-visivle item (MODIFIED_BY) value.
    So far, I have created two visual attributes and have put following code on "WHEN_NEW_BLOCK_INSTANCE" trigger
    if( :main.MODIFIED_BY = 'COCO') then
         SET_ITEM_PROPERTY('main.NAME',VISUAL_ATTRIBUTE,'VA_BLUE');
    else
         SET_ITEM_PROPERTY('main.NAME',VISUAL_ATTRIBUTE,'VA_RED');
    end if;
         But, it always goes to "ELSE" part and make RED color for all records. Could you please help me with this?
    Thanks.

    Got it.
    Post Query trigger on block
         if (:main.MODIFIED_BY ='COCO') then
              set_item_instance_property('main.NAME',current_record,visual_attribute,'VA_BLUE');
         else
              set_item_instance_property('main.NAME',current_record,visual_attribute,'VA_RED');
         end if;Thanks

  • Change background color  for JFrame

    hi,
    i want to change background color of JFrame. In my application i didn't create any panels.
    my code like this,
    Frame myFrame = new JFrame ( " Grid Layout Frame ");     
    myFrame.setSize(500,500);     
    myFrame.getContentPane().setBackground(Color.white);
    myFrame.setVisible(true);thanks,
    Balaji

    You don't get a white frame when you run this program?import java.awt.*;
    import javax.swing.*;
    public class junk
         public static void main(String[] args) throws Exception
              JFrame f = new JFrame("Hello");
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              f.setSize(500,500);
              f.getContentPane().setBackground(Color.white);
              f.setVisible(true);
    }

Maybe you are looking for

  • Unlimited Data Policy

    When I signed up with Verizon many years ago I was happy to pay for Data long before many even had it.  I have been with Verizon in one form or another since Verizon purchased AirTouch in Orange County California.  Yes, I had a bag phone and a 3 watt

  • I can't find the Info tab on iTunes on a newly purchased MacMini.  Any suggestions?

    I am a new convert to Apple..... got tired of PC and having used iPhone and iPad a couple of years decided to go the whole way. I'm having some difficulty synching my contacts however.  I remember in the PC version of iTunes that there was an info ta

  • In dialog programming i want to leave the current transaction

    Hi, In dialog programming i want to leave the current transaction and come out to the standard   sap initial screen. Please advise me how can i apply. Thanks.

  • Creating a flag based formula for Dimension

    Greetings everyone, Hopefully this is simple answer.  I have two dimensions "A" and "B" and a measure "C", where "B" is many to one attribute of "A", I would like to create a Flag formula in context that can characterise if a certain attribue of "B"

  • Adding fields in pa30 for IT 170

    hi i have added some custom  fields for infotype 170 in se11.now i want to see those fields in pa30 for that infotype 170(when i use it for a pernr in the display screen). how can i do that. any help in this regard wud be appreciated. thanks