Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: iTunes-like JTable (alternating row colors)...



The alternative to a custom cell renderer is to subclass JTable and override the 'prepareRenderer' method. This has the advantage of being able to stripe all cells, regardless of the renderer they use. The below could should work:

/**
* This overrides JTable.prepareRenderer so that we can stripe the
* rows as needed.
*/ public Component prepareRenderer(TableCellRenderer renderer,
int row, int column) {
Object value = getValueAt(row, column);
boolean isSelected = isCellSelected(row, column);
boolean rowIsAnchor = (selectionModel.getAnchorSelectionIndex()==row);
boolean colIsAnchor =
(columnModel.getSelectionModel().getAnchorSelectionIndex()==column);
boolean hasFocus = (rowIsAnchor && colIsAnchor) && hasFocus();
Component r = renderer.getTableCellRendererComponent(this, value,
isSelected, hasFocus,
row, column);
Color odd = ODD_COLOR; // make sure you have an odd color
Color even = EVEN_COLOR; // make sure you have an even color
if ( isSelected ) {
// do nothing if selected.
} else if (hasFocus && isCellEditable(row, column)) {
// do nothing if we're focused & editting.
} else if (even.equals(odd)) {
// do nothing if backgrounds are the same.
} else if ( row % 2 != 0 ) {
r.setBackground(odd);
} else {
r.setBackground(even);
}
// This is necessary to work around the 'optimization' of
// DefaultTableCellRenderer in 1.3
// See: http://developer.java.sun.com/developer/bugParade/bugs/4382860.html
if( IS_JAVA_13 ) { // make sure you have an IS_JAVA_13 constant
Color back = r.getBackground();
boolean colorMatch = (back != null) && ( back.equals(even) );
((JComponent)r).setOpaque(!colorMatch);
}
return r;
}
}

This works on all platforms and all java versions.

Thanks,
Sam
_______________________________________________
java-dev mailing list | email@hidden
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/java-dev
Be sure to read the FAQ http://developer.apple.com/java/faq/ before posting
Do not post admin requests to the list. They will be ignored.



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.