Solved

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

Posted on 2001-07-25
7
321 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
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
tomcat not starting 6 69
how to install java on RHEL image on EC2 4 41
Java: The Public Class Main 4 32
passing enum to a method 4 23
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…
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…
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 will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

830 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