Solved

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

Posted on 2001-07-25
7
306 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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

707 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

13 Experts available now in Live!

Get 1:1 Help Now