Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

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

Posted on 2001-07-25
7
Medium Priority
?
332 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
7 Comments
 
LVL 9

Accepted Solution

by:
yongsing earned 80 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 80 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 80 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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
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

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

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

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Suggested Courses

609 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