Java: CheckBoxList
I’ve been working a lot with ASP.NET recently, and the one thing .NET does miles better than Java is data-binding. In .NET if you want to show a collection as a list of checkboxes, you databind the collection to a CheckBoxList. Unfortunately, Swing doesn’t contain a CheckBoxList class but creating one didn’t take too long.
The class below provides a list of items. Use a LinkedHashMap<T, Boolean> of items to populate the list, where T, the key, is any type which can be represented by calling it’s toString() method and value is a boolean indicating the initial check state of the item.
package com.lime49.lockcrypt; import java.awt.*; import java.awt.event.*; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import javax.swing.*; import javax.swing.border.*; /** * A list of checkboxes which maintains a list of custom objects * http://www.lime49.com/ * Copyright 2009 by Harry Jennerway * All rights reserved. */ public class CheckBoxList<t> extends JList { protected static Border noFocusBorder = new EmptyBorder(1, 4, 1, 4); private CheckBoxListModel</t><t> model; /** * Initializes a new CheckBoxList with the specified object collection * @param items The items to add to the list */ public CheckBoxList(LinkedHashMap</t><t , Boolean> items) { model = new CheckBoxListModel</t><t>(items); setModel(model); addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { int index = locationToIndex(e.getPoint()); if(index != -1) { ListItem</t><t> item = (ListItem</t><t>)model.getElementAt(index); item.selected = !item.selected; revalidate(); repaint(); } } }); setSelectionMode(ListSelectionModel.SINGLE_SELECTION); setCellRenderer(new CellRenderer()); } ... } </t>
