Displaying an Image in a ComboBox

I needed to display an Image inside of a ComboBox for a recent project. The image of a selectedItem needed to appear in the ComboBox when it is collapsed and the image needed to be specified as a String.

I was surprised that a quick search didn't find any components to allow this. The closest was a post by Jason Hawryluk, however this required the image to be embedded into the application.

So I simply extended ComboBox to include an Image within it, and added some sizing calculations so it would respect padding. An example follows below:

[flash http://blog.smartlogicsolutions.com/wp-content/uploads/2008/11/ImageComboBox.swf H=150]

The ImageComboBox class

  1. Adds an Image in the createChildren method

  2. Measures the available size the image can take up in the measure method

  3. In the updateDisplayList method, if an item is selected:

  4. Sets the source for the Image

  5. Places and sizes the Image based on calculations from measure

In order to prevent the ComboBox from displaying "[object Object]" along with the image, be sure to include a label="" property on the items in the dataProvider for the ComboBox. The following code is the MXML main file for the embedded SWF above:

Example MXML

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"

	<mx:Label text="This demonstrates using the ImageComboBox" />

	<sls:ImageComboBox width="60" paddingLeft="5" paddingTop="5" paddingBottom="5">
			<mx:Object url="http://www.iconarchive.com/icons/iconshock/mario-bros/mario-32x32.png" label="" />
			<mx:Object url="http://www.iconarchive.com/icons/iconshock/mario-bros/luigui-32x32.png" label="" />
			<mx:Object url="http://www.iconarchive.com/icons/iconshock/mario-bros/start-32x32.png" label="" />
				<mx:Image source="{data.url}" />


I pushed the code into my first git repository at github. If you're a git n00b, then after you've installed git (or checked out the Git Eclipse Plugin - which I still need to do) then pull down the code by using the command:

git clone git://github.com/gjastrab/imagecombobox.git

If you aren't on the git bandwagon yet, then just right-click and save as... to download the ImageComboBox.as file for now.

I plan on improving it soon to have it respect the positioning of a label or to optionally hide the label.

Author image

About Greg Jastrab

You've successfully subscribed to SmartLogic Blog
Great! Next, complete checkout for full access to SmartLogic Blog
Welcome back! You've successfully signed in.
Unable to sign you in. Please try again.
Success! Your account is fully activated, you now have access to all content.
Error! Stripe checkout failed.
Success! Your billing info is updated.
Error! Billing info update failed.