Core Java Books

Showing posts with label desktop. Show all posts
Showing posts with label desktop. Show all posts

Tuesday, 5 November 2013

JComboBox with Highlighted AutoComplete Using Multiple Object Attributes

I haven't posted for a while especially a Swing post so here is one which may prove useful. The standard Swing JComboBox is useful but is a bit bare bones. It doesn't really cater for what the modern user expects. Thanks to Google users now expect to start typing in a text field and for multiple options to appear in the drop down as they type.

This blog sets out to provide that functionality with a slight twist in that the searching can take place on object attributes and as matches are made the matched text is highlighted in the drop down. As an example of how this might be useful, imagine a hardware store which sells many products. Each product has a product code, a name and a description. A customer might come to the shop desk asking do you have any 6 inch nails, now one shop assistant might immediately know the product code and begin to type it and the matching entry would be displayed (see below):

User enters the known product code

Now another assistant might not be aware of the exact product code but knows all nail product codes start with NW so types that and two possible nails are displayed (see below):


User enters NW which all nail product code start with

So the combo box can search on the product code but also it searches on the product name. If a customer comes in to the shop and starts asking about wood, the assistant can enter 'wood' in to the field and a list of product with 'wood' in the name will be shown (yes I know there aren't many products in my shop!)

User enters 'wood' and that matches on two products names

Ah but the customers was only interested in Birch wood. Now in this example somebody forgot to put Birch in the product name but each product also has a description, maybe birch will be in the description of one of the products so the assistant types 'birch':

User enters 'birch' and now a match is found against a products description

So the field has now found a match on a product description, it would have shown multiple products if any other matches had been found. As an example if the user just enters the character 'a' that matches on multiple products via the codes and names.

Match on 'a' matches codes and names

As can be seen the field both autocompletes as the user types and also highlights on the string that it is matching on against each product.


So how is this achieved ?

Firstly I've decided not to copy out the code in the blog, you can check it out by downloading it in the link below. Instead I will describe how the code was put together to achieve what I wanted.

Firstly I created a data class called Product, this simply has get methods on it for code, name and description. For the demo I created a handful of Product object instances to allow the JComboBox to be tested.

I then created a class called ProductWordMatch, this has get methods for matchingString and Product. An instance of ProductWordMatch is created for each Product that has a match on code, name or description for what the user has typed so far. This class is used by the JComboBox model, more on that soon.

I then created a the ProductComboModelHelper class. Simply put this class is given the complete list of Products and when a user types a key is scans though the Products building up a list Products that have a match and for each unique one creates a new instance of ProductWordMatch. It then loads the ProductWordMatch instances into a ListComboBoxModel<ProductWordMatch>. In effect as the user is typing the model used by the JComboBox is being updated.

I next created a RegexTestHighlightPainter, this class extends the SwingX libraries AbstractPainter. This painter is used within the JComboBox drop down to highlight matching text on each matching product. As can be seen by the pictures it highlights the matching text in Orange. The painter is used to paint the background of a JXLabel which is used by the JComboBox renderer.

I finally created the ProductComboBox class which extends JComboBox. This class makes use of unique renderer and editor classes to display the items in the drop down. The Renderer uses two JXLabels, one used on the left for displaying product codes and names and one on the right to display the matching text string, this label also has the RegexTestHighlightPainter set as a background painter. The KeyType and KeyPress methods are also overridden so that as the user types the model is updated using the ProductComboModelHelper and matching data and the editor text are updated as appropriate.

Try the WebStart code to see what it's all about. If it doesn't work for you due to security permission download the code and unzip it so you can take a look and build it yourself.

There are lots of enhancements that could be made to make the code more flexible and also more performant if a lot of products existed. Also the demo simply uses products as a way of showing what the JComboBox is capable of but it could be used for many many other tasks.




Try it out (Webstart security permissions might cause issues with later versions of java):





You can download the code from here have a look and figure it out.

Please give a recommend below if you liked the article.

Wednesday, 2 March 2011

JTextFields and Regex Documents

I had planned on writing a post about auto complete JCheckBoxes but before this I've decided to jot down some notes on a simple regular expression document class I've written for handling text entry on text fields.

As they say there are many ways to skin a cat and this is just a simple way for me to restrict the number of characters entered into a fields and also the characters that can be typed by making use of a regular expression. I know there are other ways of doing this but I think this offers a nice example of what you can start doing with Document classes and how useful they can be. To get really fancy you could also investigate the JFormattedText component and see how you can restrict user input and focus traversal but for now I will comment on JTextField and keep things light.

In the examples I allow a user to enter a 'Caller Number', 10 characters are allowed. The characters can be any mixture of digits, space, + or -. They can also enter a 'Caller Code' and here they are allowed to enter up to 2 characters which can be A to E or 1 to 7.

The regex expressions used are:

"[0-9 \\-\\+]+"

and

"[A-E1-7]"

Try it out:




(Java 1.6 required!)

I achieved this by extending the Document class with a MaxLengthDocument class that restricts the number of characters than can be entered. I then extended the MaxLengthDocument class with RegexDocument class which makes use of the Matcher and Pattern classes in the Regex package.

I simply set the Document on  the two JTextField's, for example:

callerNumberTF.setDocument(new RegexDocument("[0-9 \\-\\+]+", 10));

See the code below.

The MaxLengthDocument:



package com.webbyit.swing;

import java.awt.Toolkit;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 * Simple Document class that restricts input on the associated text field to a
 * specified maximum length.
 *
 * @author webbyit
 *
 */
public class MaxLengthDocument extends PlainDocument {

    /**
     * Maximum length of the text
     */
    private final int maxLength;

    /**
     * Default constructor.
     *
     * @param maxLength
     *            the maximum number of characters that can be entered in the
     *            field
     */
    public MaxLengthDocument(final int maxLength) {
        super();
        this.maxLength = maxLength;
    }

    @Override
    public void insertString(final int offset, final String str,
                             final AttributeSet attr) throws BadLocationException {
        if (getLength() + str.length() > maxLength) {
            Toolkit.getDefaultToolkit().beep();
            return;
        }
        super.insertString(offset, str, attr);
    }
}

The RegexDocument:



package com.webbyit.swing;

import java.awt.Toolkit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;

/**
 * Class to provide restriction on user input using a regex pattern.
 *
 * @author webbyit
 *
 */
public class RegexDocument extends MaxLengthDocument {

    protected final Pattern pattern;

    /**
     * Contructor used to construct a document object which pattern matches
     * strings as typed.
     *
     * @param regex
     *            pattern to match on typed strings
     * @param maxLength
     *            maximum length of full string
     */
    public RegexDocument(final String regex, final int maxLength) {
        super(maxLength);
        this.pattern = Pattern.compile(regex);
    }

    @Override
    public void insertString(final int offset, final String str,
                             final AttributeSet attr) throws BadLocationException {
        final Matcher matcher = pattern.matcher(str);
        if (matcher.matches()) {
            super.insertString(offset, str, attr);
        } else {
            Toolkit.getDefaultToolkit().beep();
        }
    }
} 

Now this should give you enough info to start delving into documents and working out how you want to use them :)

Enjoy

Monday, 28 February 2011

JCheckBox and Icons

I've been working on an application which makes extensive use of JCheckBox. In all cases I override the icons displayed by JCheckBox class to more user friendly and modern looking. The standard icons used by Swing L&F (including Nimbus) are OK but they don't really offer much goodness to the eye. Here is an example of a JCheckBox with some interesting icons:






(Java 1.6 required!)

The icons also brighten slightly when the mouse moves over them.

As several of these JCheckBoxes display the same icons I decided a nice solution would be to create some classes that override JCheckBox so I can easily make use of common settings and within an IDE (such as Netbeans) just drag and drop the widgets around.

I started by creating an AbstractIconCheckBox

This class provides a base with most of the logic in it to construct the widget. Note that it also provides a constructor which takes care of sizing the icons to be display.



package com.webbyit.swing;

import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;

/**
 * Abstract base <code>JCheckBox</code> which is intended to be used to display icons.
 * 
 * @author webbst
 */
abstract public class AbstractIconCheckBox extends JCheckBox {

    private static final int DEFAULT_ICON_SIZE = 16;

    /**
     * Creates a <code>JCheckBox</code> initially de-selected and displaying tick and cross icons
     * of default size of 16 pixels height and width.
     */
    public AbstractIconCheckBox() {
        super();
        setIcons(DEFAULT_ICON_SIZE);
    }

    /**
     * Creates a <code>JCheckBox</code> initially de-selected and displaying tick and cross icons.
     *
     * @param iconSize the height and width of the tick and cross icons to be displayed
     */
    public AbstractIconCheckBox(int iconSize) {
        super();
        setIcons(iconSize);
    }

    /**
     * Set the icons on the <code>JCheckBox</code>
     */
    protected void setIcons(int iconSize) {
        try {
            BufferedImage image = ImageUtilities.getBufferedImage(getSelectedIconName());
            setSelectedIcon(new ImageIcon(ImageUtilities.createScaledImageFast(image, iconSize)));
            image = ImageUtilities.getBufferedImage(getRolloverSelectedIconName());
            setRolloverSelectedIcon(new ImageIcon(ImageUtilities.createScaledImageFast(image, iconSize)));
            image = ImageUtilities.getBufferedImage(getIconName());
            setIcon(new ImageIcon(ImageUtilities.createScaledImageFast(image, iconSize)));
            image = ImageUtilities.getBufferedImage(getRolloverIconName());
            setRolloverIcon(new ImageIcon(ImageUtilities.createScaledImageFast(image, iconSize)));
        } catch (IOException ex) {
           System.out.println("Icon not found in TickCrossCheckBox class" + ex);
        }
    }

    abstract protected String getSelectedIconName();

    abstract protected String getRolloverSelectedIconName();

    abstract protected String getIconName();

    abstract protected String getRolloverIconName();
}



All any implementing class then needs to do is to implement the abstract methods which provide the icons. As the TickCrossCheckBox demonstrates:



package com.webbyit.swing;

/**
 * <code>JCheckBox</code> which displayed a tick or cross image instead of the normal box with a cross in it.
 * 
 * @author webbst
 */
public class TickCrossCheckBox extends AbstractIconCheckBox {

    /**
     * Creates a <code>JCheckBox</code> initially de-selected and displaying tick and cross icons
     * of default size of 16 pixels height and width.
     */
    public TickCrossCheckBox() {
        super();
    }

    /**
     * Creates a <code>JCheckBox</code> initially de-selected and displaying tick and cross icons.
     *
     * @param iconSize the height and width of the tick and cross icons to be displayed
     */
    public TickCrossCheckBox(int iconSize) {
        super(iconSize);
    }

    @Override
    protected String getSelectedIconName() {
        return "tick_32.png";
    }

    @Override
    protected String getRolloverSelectedIconName() {
        return "tick_32_rollover.png";
    }

    @Override
    protected String getIconName() {
        return "cross-32.png";
    }

    @Override
    protected String getRolloverIconName() {
        return "cross-32_rollover.png";
    }
}


I also have implementing classes for such things as sound mute checkboxes and so on.

I'm intending that my next post will look into developing an AutoComplete JComboBox. I've seen it done a few times before but I want to try something a little different. It should prove an interesting challenge and provide a useful component. I'll start with a teaser WebStart link and then write a few blogs about how I get it working.