Core Java Books

Showing posts with label gui. Show all posts
Showing posts with label gui. 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.

Tuesday, 5 April 2011

Java GUI Application Shutdown Gotcha

In recent times I've had issues with one or two Java GUI application not shutting down when I close them. They seem to stay around as a process, consuming computer resources. Today I got to the bottom of the problem and it's a bit of a nasty gotcha which I wasn't aware of before so I thought I would share it.

In theory when you close a Java application all the threads should be stopped and the process should die. Im my case when I monitored the application the threads I expected to finish such as Swing worker pools were still alive, Strange. The reason turned out to be that the AWT Shutdown thread wasn't terminating all the helper threads, and the reason for this was that there were still AWT Events in the EventQueues. The reason for this is a real sneaky little gatcha, I will explain.

My application used a Thread which had a regular sleep but when woke up would so some calculation and then make a call to update the gui:

Thread updateThread = new Thread(new Runnable() {

  @Override
  public void run() {
    int i = 0;
    do {
      try {
        Thread.sleep(300); // 300ms
        gui.updateValue(SOME_VALUE);
      catch (InterruptException ex) {
        return;
      }
      frame.setValue(SOMEDATA);
    while (i++ < 100);
  }


}"updateThread");

updateThread.setDaemon(true);
updateThread.start();

Now you will notice that the thread returns if it is interrupted and also it is started as a Daemon thread. I had thought that as part of the application shutdown the thread would be terminated but NO it wasn't. This was caused by gui.updateValue(SOME_VALUE) making use of InvokeLater:



  public void updateValue(final int value) {

        // make sure we access graphics in the EDT thread
        java.awt.EventQueue.invokeLater(new Runnable() {

          @Override
            public void run() {
                try {
                     ...
                     ...
                     ...
                    SOME CODE
                catch (Exception t) {
                    // not a lot to do
                }
            }
        });
    }

The InvokeLater is basically putting an event on the EventQueue and because of this the AWT Shutdown thread want shutdown the application. The AWT Shutdown thread checks the EventQueues every seconds but as you will see my Thread does an update subsecond (300ms) so there is always an event on the Queue! So in short the AWT Shutdown thread never terminates the threads I want it to terminate and so the application needs to be killed.

The work around is simple in the while loop of my thread I also check that the JComonent that is to be updated via it is still visible and shown, if it is not the loop is exited, the thread dies and so there are no more events put on the Event thread and whooohooo the application closes as expected :)


Thread updateThread = new Thread(new Runnable() {

  @Override
  public void run() {
    int i = 0;
    do {
      try {
        Thread.sleep(300); // 300ms
        gui.updateValue(SOME_VALUE);
      catch (InterruptException ex) {
        return;
      }
      frame.setValue(SOMEDATA);
    }while (i < 100 && progressGlassPane.isVisible() && progressGlassPane.isShowing());
  }
}"updateThread");
updateThread.setDaemon(true);
updateThread.start();


So in short don't call InvokeLater from a helper thread at sub-second frequency unless you also terminate the thread if the component it is updating is no longer visible!
 
As a side note after I spotted the issue I found this very useful article on the same subject which highlighted the same issue I was having.

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.