Saturday, September 12, 2009

Country Flag Decorations On Your Swing Components

Here is how to get country flag icon decorations on your JTable cells, JList cells, JCombobox'es and JTextFields.

First you need to grab the Flag Icons from the famfamfam site and package them into a jar file and add it to your classpath. The JTextField flag decoration is done via the BuddySupport in the xswingx project.

Then we need to set up a mapping of country names to famfamfam icon names like this:

private final String[] countries = { "AFGHANISTAN", "AF", "Ă…LAND ISLANDS",...}
Map<String, String> countryMap = new HashMap<String, String>();
for (int i = 0; i < countries.length;) {
countryMap.put(countries[i], countries[i + 1]);
i += 2;
countryFlagDecorator = new CountryFlagDecorator(countryMap);
// lazy do CountryFlagDecorator.getInstance() and skip the above mapping setup

Now we can decorate e.g., a JCombobox like this:

JComboBox flagCombo = new JComboBox(new String[] { "DENMARK", "SWEDEN",
"NORWAY" });

A JTable cell like this:

JTable jt = new JTable(data, fields);
TableColumn col = jt.getColumnModel().getColumn(2);
col.setCellRenderer(new CountryFlagTableCellRendere(
col.setCellEditor(new CountryFlagCellEditor(countryFlagDecorator,
new String[] { "DENMARK", "SWEDEN", "NORWAY" }));

A Jlist (with a small twist)

JList flagList = new JList(new String[] { "DK", "SE", "NO", "US" });
flagList.setCellRenderer(new CountryFlagListCellRendere(
countryFlagDecorator, new CountryNameConverter() {
public String convertCountryName(String countryName) {
if ("DK".equals(countryName)) {
return "DENMARK";
} else if ("SE".equals(countryName)) {
return "SWEDEN";
} else if ("NO".equals(countryName)) {
return "NORWAY";
} else if ("US".equals(countryName)) {
return null;

And a JTextField like this:

JTextField flagField = new JTextField("");
PromptSupport.setPrompt("Write name of a country, e.g., DENMARK", flagField);
countryFlagDecorator.addCountryFlag(flagField, null);

Download the source


Anonymous said...

Please FIX your JNLP link. On Firefox/Linux, this won't start and on my system a simple jnlp link work.

mchiareli said...

works for me with ubuntu 9.04 / firefox 3.0.

Great work, thanks....

Live Traffic Map