?
Solved

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

Posted on 2001-07-25
7
Medium Priority
?
327 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
Get real performance insights from real users

Key features:
- Total Pages Views and Load times
- Top Pages Viewed and Load Times
- Real Time Site Page Build Performance
- Users’ Browser and Platform Performance
- Geographic User Breakdown
- And 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
Suggested Courses
Course of the Month10 days, 3 hours left to enroll

762 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