Solved

is it possible to make different colors for JTable rows dyanmically?.

Posted on 2001-07-25
7
315 Views
Last Modified: 2011-10-03
is it possible to make different colors for JTable rows dyanmically?. please give me a sample code?.
0
Comment
Question by:mmsreddy
7 Comments
 
LVL 9

Accepted Solution

by:
yongsing earned 20 total points
ID: 6316370
This example will set odd rows background color to yellow, and even rows background color to white.

// Define your own table cell renderer:

TableCellRenderer tableCellRenderer = new TableCellRenderer() {
     public Component getTableCellRendererComponent(JTable table, Object value,
         boolean isSelected, boolean hasFocus, int row, int column) {
        JLabel label = new JLabel();
        label.setOpaque(true);
        label.setFont(new Font("Dialog", Font.PLAIN, 12));
        if (value != null) label.setText(value.toString());

        // set cell's foreground to default cell foreground color
        label.setForeground(table.getForeground());

        // if cell is selected, set background color to default cell selection background color
        if (isSelected) label.setBackground(table.getSelectionBackground());
        else {
              // set odd rows background to yellow
              if (row % 2 == 0)  label.setBackground(Color.yellow);

              // set even rows background to white
              else label.setBackground(Color.white);
        }

        // draw border on cell is it has focus
        if (hasFocus) label.setBorder( UIManager.getBorder("Table.focusCellHighlightBorder") );

        // position cell text at center
        label.setHorizontalAlignment(SwingConstants.CENTER);

        return label;
    }
};


// Traverse through all table columns (assume total of 5), and set the renderer to each column
for (int i = 0; i < 5; i++) {
    // Get each table column
    TableColumn tableColumn = table.getColumnModel().getColumn(i);

    // Set our own table cell renderer for each table column.
    tableColumn.setCellRenderer(tableCellRenderer);
}
0
 
LVL 92

Assisted Solution

by:objects
objects earned 20 total points
ID: 6316404
As the renderer gets called once for every visible cell, creating a label every time will slow down as the table size increases due to excessive object creation (and gc).
A way around this would be to have your renderer extend JLabel, and just return this.

public class MYRenderer extends JLabel
implements TableCellRenderer
{
    public Component getTableCellRendererComponent(
       JTable table, Object value, boolean isSelected,
       boolean hasFocus, int row, int column)
    {
       .....
       return this;
    }
}

(In fact the DefaultTableCellRenderer does exactly this and is often a useful base class for simple renderers).
0
 
LVL 4

Assisted Solution

by:kylar
kylar earned 20 total points
ID: 6319120
Another point to make is that it is almost always better to extend DefaultTableCellRenderer , which, for performance reasons overrides  validate, revalidate, repaint, and firePropertyChange  to be no-ops for performance reasons. If you extend JLabel or anything else, you should consider doing this as well ( if you are rendering any amount of  rows, the validation overhead can be prohibitive).

Cheers,
Kylar
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 92

Expert Comment

by:objects
ID: 6320170
> almost always better to extend DefaultTableCellRenderer

Assuming of course that you want a label to render your cell :)
0
 
LVL 92

Expert Comment

by:objects
ID: 6324666
> overrides  validate, revalidate, repaint, and
> firePropertyChange  to be no-ops for performance
> reasons.

As the component is never added to anything and just used for 'rubber-stamping' I don't see how this will improve performance?
0
 
LVL 4

Expert Comment

by:kylar
ID: 6327485
This is the way that the hierarchy works: When the table renders the component, it calls setBounds() which triggers calls to invalidate, repaint and it can also call to firePropertyChange. There is no need to deal with the overhead of these calls, so we just make them no-ops to speed performance. It will try to get it's parent, and go up the hierarchy if we let it, but since we know that it doesn't have any parents, and that it will never need to be validated, (since JTable's CellRendererPane will call paintComponent directly) we can safely override them and reap the benefits.
Cheers,
Kylar
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 9017507
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:


[split points between yongsing,kylar and objects]


Please leave any comments here within the next seven days.
 
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
 
sudhakar_koundinya
EE Cleanup Volunteer
---------------------
If you feel that your question was not properly addressed, or that none of the comments received were appropriate answers, please post your concern in THIS thread.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

932 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now