Posts from January 2009

Jan
20
2009

Java: CheckBoxList



Posted in Programming

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>

Download CheckBoxList.java
Read more »

Jan
5
2009

Default wizard button in ASP.NET



Posted in Uncategorized

When you press enter/return on a wizard control in ASP.NET, the default action is to just submit the form, disregarding any buttons which were pressed. This seems pretty counter-intuitive to me – if I press enter on a form, it should be obvious I want to go ‘Next’. After two hours trying to debug an installer wondering why it seemed to work sometimes and not others I eventually tracked it down to the default button. I’m using a master page, but the principle is the same if you’re not.

The method I used uses the Page_Load event to set the default button for the form.

Read more »