Core Java Books

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.

Saturday, 23 March 2013

I'm Back!

Well it's been a while!

I've was writing a Android application last time I posted on here and then got a contract working on Java Web based development which was all new to me. My Android app is currently in deep freeze but is about 75% complete. I think when it is complete it will be very useful to me and a few other people so some day it will be released. I suspect when I start work on it again there will be a bit of effort bringing up to date with the latest Android changes and I'll have to think about making it good to use on a tablet also.

So whats next on here. Well I've been working on the development of web application which provides a fancy almost application looking web based front end to the user using GXT which is basically GWT with a slight fancier looking style and some extra widget. Check out these technologies they are very smart. Basically you write the browser based front ends in Java and it is compiled in to html and javascript. It very similar to writing Swing type code but it runs in the browser using HTML and Javascript. You don't need to be a HTML or Javascript Ninja which personally I have no intention of being. It's useful to know the basics and perhaps a little CSS to help you with the style of components ut that is about it.

So I plan to write some blogs about what I've been learning and using recently and some general observations about Java server development.

By the way if you are interested in GWT I can highly recommend a new book which was only recently released. It is a bit of a brick however it covers everything in fine detail.

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.