Code
class MultiColumnCellRenderer extends JPanel implements ListCellRenderer{
private final JLabel leftLabel = new JLabel();
private final JLabel rightLabel;
public MultiColumnCellRenderer(int rightWidth) {
super(new BorderLayout());
this.setBorder(BorderFactory.createEmptyBorder(1,1,1,1));
leftLabel.setOpaque(false);
leftLabel.setBorder(BorderFactory.createEmptyBorder(0,2,0,0));
final Dimension dim = new Dimension(rightWidth, 0);
rightLabel = new JLabel() {
@Override public Dimension getPreferredSize() {
return dim;
}
};
rightLabel.setOpaque(false);
rightLabel.setBorder(BorderFactory.createEmptyBorder(0,2,0,2));
rightLabel.setForeground(Color.GRAY);
rightLabel.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(leftLabel);
this.add(rightLabel, BorderLayout.EAST);
}
@Override public Component getListCellRendererComponent(
JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
LRItem item = (LRItem)value;
leftLabel.setText(item.getLeftText());
rightLabel.setText(item.getRightText());
leftLabel.setFont(list.getFont());
rightLabel.setFont(list.getFont());
if(index<0) {
leftLabel.setForeground(list.getForeground());
this.setOpaque(false);
}else{
leftLabel.setForeground(
isSelected?list.getSelectionForeground():list.getForeground());
this.setBackground(
isSelected?list.getSelectionBackground():list.getBackground());
this.setOpaque(true);
}
return this;
}
@Override public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
return new Dimension(0, d.height);
}
@Override public void updateUI() {
super.updateUI();
this.setName("List.cellRenderer");
}
}
References
No comments:
Post a Comment