Core Java Books

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

Thursday, 5 January 2012

Swing to Android

Well its been a while since I updated my blog. Basically I finished a contract back in June last year and decided to take some time off. I've been doing anything other that work really :) Actually I have been doing some of my own programming projects to keep my hand in, basically a bit of Swing and a fair bit of Android. I plan to start looking around for new Contracts again shortly.

I plan to have my first Android App out in the next month or so and around that time I will start posting on some of the more technical issues about the Android Eco System and some of the problems I came across and how I resolved them.

In the meantime here is a quick, brief 10,000ft overview/observations on Android from a Swing developers point of view.

Firstly if your coming to Android from Swing you are approaching it with a big advantage to J2EE developers. Now I realise Android doesn't actually have the AWT/Swing API's but that doesn't matter as the general front end/event driven mechanism in it is so close to Swing that you will find it easy. Now Android does rely a lot more on XML defs than Swing ever did and that took me a while to get my head around and realise how powerful a feature it actually it is if used correctly.

I started off by buying a couple of books:




Learning Android
Programming Android

I'd recommend both of these as they cover the basics very well, from then on you can use the online Android SDK docs. Other books I've seen are not great to be honest, you will be better off googling.

Android GUI is like Swing, it's on a single thread, if you do some heavy lifting on that thread it will cause some issue's just like with Swing. There are mechanisms and classes available that like SwingWorker help you out (more of this in later blogs).

A typical Android screen is created by an Activity class that you have extended. This class typically inflates an XML definition on the screen layout. The XML defines the textfields, comboboxes (called Spinners) and so on. Eclipse is typically used to create the XML (I use the Graphical Layout Tool in Eclipse which is still very buggy but ok). You can also hard code the layouts but I wouldn't bother as it's easier to use the XML. The Activities are state driven, they are created, paused, resumed and so on. The states are there because they run on a small device where calls can come in, other programs started an so on. The screens for your app can be hidden, displayed again, killed off and restarted .... You need to handle this and in some cases persist the data.

The Activity states are a bit of a head scratcher to start with but once you try a few examples out its straightforward enough.

Handling Events from components (Views in Android) is so similar to Swing it makes me wonder if somebody copied the event mechanism ;)

Any Activity you create needs to be defined in your applications Manifest file, this file is used by the Android device to figure out you apps main class, the icon, the privileges it needs and so on. If you don't specify an Activity on the manifest then the app will stack trace when you attempt to display it.

Jumping from screen to screen is done by the use of Intents. Intents are used by Android to signal that you want something to happen. You can create an Intent passing in the class that you want to process the Intent (so say an Activity which displays another screen) or you can ask for some operation, so for instance display this web page, Android in this case would open a browser and display the page. If you had several browsers installed it might ask you which one to use. Android keeps an internal stack so that when the back key is pressed then it will switch back from the browser back to your apps Activity (remember the states I mentioned, your Activity has just had its resume state called ;).

Android has some nice features to let you define backgrounds and the look of buttons. This seems to be similar to JavaFX. Basically you can define gradients, patch 9 images (a way of taking a small image and extending it to fit a background nicely), shapes .......

Android comes complete with SQLite3 which is a nice lightweight database. I've found it very quick and nice to use. I'll return to this in another blog as I'm not sure the preferred way to use the database in the most books is actually a good idea.

Finally there is a emulator to test your apps on. Its ok, lets you test things on different versions of android and different device specs (screens, memory, input methods (rollers, soft/hard keyboard)) but its slow and really I'd say if you want to really write and app you need atleast one Android device. I have a nice Nexus S Mmmmmm lovely.

Anyway thats a very brief overview and when I finish my App I will have some time to spend adding some nice new blogs.

Enjoy

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.

Wednesday, 16 March 2011

Java Tables: Simple Column to Row Highlighting

In this post I show a simple solution for highlighting table rows based on the value in a particular column on the row.





(Java 1.6 required!)

Firstly I make use of SwingX libraries which provide highlighting functionality. I replace the normal JTable with a JXTable and then add a Highlighter to the table.

The highlighter (code below) is given a column name and two maps for background and foreground colors. The map is keyed on a String with color values. The highlighter takes the value of the specified column on each row and that is used to get the colors required for highlighting



package com.webbyit.swing;

import java.awt.Color;
import java.awt.Component;
import java.util.Map;
import org.jdesktop.swingx.JXLabel;
import org.jdesktop.swingx.decorator.ComponentAdapter;
import org.jdesktop.swingx.decorator.HighlightPredicate;
import org.jdesktop.swingx.painter.Painter;
import static org.jdesktop.swingx.color.ColorUtil.blend;

/**
 *
 @author webbyit
 */
public class ColumnToRowHighlighter extends ColorBlendHighlighter {

    protected Map<String, Color> foregrounds;
    protected Map<String, Color> backgrounds;
    protected String columnName;

    public ColumnToRowHighlighter(String columnName, HighlightPredicate predicate) {
        this(columnName, predicate, null, null);
    }

    public ColumnToRowHighlighter(String columnName, HighlightPredicate predicate, Map<String, Color> backgrounds,
                                  Map<String, Color> foregrounds) {
        super(predicate);
        this.backgrounds = backgrounds;
        this.foregrounds = foregrounds;
        this.columnName = columnName;
    }

    public void setForegrounds(Map<String, Color> foregrounds) {
        this.foregrounds = foregrounds;
    }

    public void setBackgrounds(Map<String, Color> backgrounds) {
        this.backgrounds = backgrounds;
    }

    @Override
    protected void applyBackground(Component renderer, ComponentAdapter adapter) {
        if (backgrounds != null) {
            Color color = null;
            if (adapter.isSelected()) {
                color = getBackground();
            else {
                int columnIndex = adapter.getColumnIndex(columnName);
                String str = adapter.getFilteredStringAt(adapter.row, columnIndex);
                color = backgrounds.get(str);
            }
            if (color != null) {
                if (renderer instanceof JXLabel) {
                    // might have a background painter
                    Painter painter = ((JXLabelrenderer).getBackgroundPainter();
                    renderer.setBackground(blend(renderer.getBackground(), color));
                else {
                    renderer.setBackground(blend(renderer.getBackground(), color));
                }
            }
        }
    }

    @Override
    protected void applyForeground(Component renderer, ComponentAdapter adapter) {
        if (foregrounds != null) {
            Color color = null;
            if (adapter.isSelected()) {
                color = getSelectedForeground();
            else {
                int columnIndex = adapter.getColumnIndex(columnName);
                String str = adapter.getFilteredStringAt(adapter.row, columnIndex);
                color = foregrounds.get(str);
            }
            if (color != null) {
                renderer.setForeground(blend(renderer.getForeground(), color));
            }
        }
    }
}

To make use of the highlighter a JXTable must be used instead of a JTable, to be honest I don't use JTables anymore I always use JXTable. This is how the highlighter in the demo is added:



Map<String, Color> backgrounds = new HashMap<String, Color>();
backgrounds.put("Visa", Color.BLUE);
backgrounds.put("Cash", Color.RED);
backgrounds.put("Cheque", Color.BLACK);
Map<String, Color> foregrounds = new HashMap<String, Color>();
foregrounds.put("Visa", Color.WHITE);
foregrounds.put("Cash", Color.YELLOW);
foregrounds.put("Cheque", Color.ORANGE);

// Use default predicate
ColumnToRowHighlighter highlighter = new ColumnToRowHighlighter("Payment Method", HighlightPredicate.ALWAYS,
      backgrounds, foregrounds);
table.addHighlighter(highlighter);

Notice that the highlighter allows a predicate to be set. This is another feature which provides the capability to filter when a highlight is used or not. In the example for instance I could have provided a predicate which defines the highlights is only used for balances outstanding over 50. It's worth searching around for article elsewhere on SwingX and highlighting as its very flexible and very easy to use.

Enjoy.

Tuesday, 15 March 2011

Displaying Application and Java Details in an About JDialog

I've decided that this post will offer a demonstration of a basic about dialog which displays basic information about the application and also about the java platform. Treat it as a starting point for you to extend and tweak.





Download the main frame and dialog source code to see how its done, its very simple. Please note I used Netbeans to create the code.

You could extend the code to display a company logo, provide a copy button on the Java details so they could be posted in an email ...................................

Enjoy :)

Thursday, 10 March 2011

JInternalFrame's Parent & Child Modality

This post is about managing JInternalFrame's within a JDesktopPane, specifically the ability to popup child JInternalFrame's from a parent JInternalFrame's. Now why would you want to do this you may ask? Well on several applications I have worked on users open forms to view/enter data, these forms then offer extra buttons to view related data in other forms. In many cases I require that the new form blocks the parent form, in short becomes modal to the parent form (not other forms).

This post offers code and a demo of a simple extension to JInternalFrame which controls the child and parent relationship. It also offers non desktop modal dialogs, but dialogs that are only modal to the parent JInternalFrame.

The functionality the provided specifically is:

  1. Frames can open child frames. The parent frame becomes busied out (lightweight modal).
  2. Clicking on a busied out parent frame brings the top related child frame to the front.
  3. Multiple parent and child hierarchy's can be on the desktop at one time.
  4. A frame can open a dialog, the dialog can be either desktop modal or modal just to the frame hierarchy it was opened from.
  5. A frame modal dialog will be brought to the front if any of its parent frames are clicked on.
Please try out the demo, the list below gives some idea of the functionality.



Play around with the demo, the menu lets you open many frames that are not related. Each frame then has buttons to let you open different children. Notice how you can click on different children and children of children and also busied out parents, you will see that the top most child frame of the associated from clicked is always brought to the front, even if iconized.

I think many people will find this functionality useful in JDesktopPane related applications

Try it out:




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

Basically I have overridden JInternalFrame and added functionality to listen out for child frames opening and closing. This caused glassplanes to be installed or removed as appropriate.  Check out the logic, its easy(ish) to follow. Let me know if you can think of other uses or extensions to this.


In future I will create a post to demonstrate full modality for internal frames ;)

UPDATE: AUG 2016 - Google have retired the Google Drive Archive :( If you wish to obtain the code please email me and I can send it via email or you can obtain the whole archive here.

Please give a recommend below if you liked the article.

Monday, 7 March 2011

Nimbus L&F JDesktopPane Background Performance Tweak

This blog is for all the people out there using the Nimbus L&F and who find that it has a performance hit when using JDesktopPane components.

I had performance problems on a lightweight application using JDesktopPane's  and I tracked it down to the amount of processing going on when the background of the pane was repainted. Nimbus paints the background using what looks like vector type drawing routines to paint a fancy background pattern. This is all very impressive but on a client with a low(ish) spec processor this has a major impact whenever the user moved or resized JInternalFrame's.

I changed the background Painter used by the JDesktopPane to simply fill the pane with the Nimbus background color. This improved the performance significantly in my case and also left more processing available for the rest of the application to use.

Below is images of the before and after shots on the simple demo application.

Original Nimbus
Updated Background Painter




For the demo code I have simply overriden the updateUI() method on the JDesktopPane to simply provide a new Painter which does a simple fill using the default color.


package com.webbyit.swing;

import com.sun.java.swing.Painter;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import javax.swing.JDesktopPane;
import javax.swing.UIDefaults;
import javax.swing.UIManager;

/**
 * A <code>JDesktopPane</code> that displays a simple fill <code>Color</code> as the
 * background when the nimbus l&f is being used. This saves many process cycles over the normal
 * background painting that makes use of vector drawing.
 *
 @author webbyit
 */
public class SimpleFillDesktopPane extends JDesktopPane {

    @Override
    public void updateUI() {
        if ("Nimbus".equals(UIManager.getLookAndFeel().getName())) {
            UIDefaults map = new UIDefaults();
            Painter<JComponent> painter = new Painter<JComponent>() {

                @Override
                public void paint(Graphics2D g, JComponent c, int w, int h) {
                    // file using normal desktop color
                    g.setColor(UIManager.getDefaults().getColor("desktop"));
                    g.fillRect(00, w, h);
                }
            };
            map.put("DesktopPane[Enabled].backgroundPainter", painter);
            putClientProperty("Nimbus.Overrides", map);
        }
        super.updateUI();
    }
}



And here is a quick demo for you to try it on your box. You should find if you expand the window to be full frame and move the internal frame around it should redraw fairly quick on a low spec box.




(Java 1.6 required!)

Friday, 4 March 2011

Using Java2D to Create Icons at Runtime

I needed some marker Icons to display unique points on a map. Each icon needed to have a unique id so I wanted a number or letter to be placed on each icon. Obviously I did not want to create and store hundreds of icons in a directory, the simple solution would be to create them on the fly using Java2D.

I'm posting a basic solution which creates some fairly basic marker icons but it is a good starting point for people to start creating more fancy looking markers/icons/images.

Basically I make use of Java2D to draw into BufferedImage and then use the image to construct an ImageIcon.

The example code can be downloaded and creates the following demo images:


Now obviously this isn't created by anyone with artistic talent but it shows the basics.


Click on the following button to try it out.



(Java 1.6 required!)

I'd be interested to hear about any other solutions and any neat ways of extending this.

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 attrthrows 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 attrthrows 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.