Friday, June 29, 2007

HOWTO: add stripes to JList

Overview
Swing has one pretty cool thing. You can customize everything to look anyway you want. The following will show you a simple but useful trick for adding strips to a swing JList component.

Technique
The following class can be put right into a project. You will want to change the package name though. This is all you need to do the striping. Towards the bottom, you will see two setBackground(...) calls. The first is if a row is even and unselected and the other is if the row is even but is selected. Play with the colors until you find ones you like. I am not sure I like the ones below actually.
package jliststriping;

import javax.swing.*;
import java.awt.*;

public class StripeRenderer extends DefaultListCellRenderer {
public Component getListCellRendererComponent(JList list,
Object value, int index, boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(
list,
value,
index,
isSelected,
cellHasFocus
);

if(index%2 == 0) {
if(! list.isSelectedIndex(index)) {
label.setBackground(new Color(230,255,230));
} else {
label.setBackground(new Color(255,255,200));
} // end-if
} // end-if

return label;
}
} // end-class
Once you have this code in your project, the next step is to plug it into your JList. In Netbeans, you simply:
  1. Select your JList in Matisse
  2. In Properties, look for cellRenderer. Click on the "..."
  3. Using "Select Mode" "Form Connector" select "User Code"
  4. type new StripeRenderer() in the text box.
  5. Click Ok and test it out.
If you don't have Netbeans, you can add jList.setCellRenderer(new StripeRenderer()); in your jList creation code block.

Final Thoughts
Adding stripes can make the component easier to read. This code is cut/paste - able into a Java file for use in any program. Give it a try.

No comments: