NetBeans, XML and ComboBox

At last I found out how to use an XML file to populate a Swing ComboBox. If you know how to do it, it’s fairly easy. As always.

Things you need:

Look carefully at the file names.xsd. It’s the start of the whole process. You make your XSD files as follows:
First make your XML data file as you would like it to be. It must be validated (you can do that online: there are some sites that validate XML for you). From this XML file you can generate an XSD file, also online or with soms nifty XML editor like Stylus. Whatever you want.
Then you start editing your XSD file. Here we go:

  • Make the heading to look as much like my names.xsd file.
  • if you would need some special code in your class, you need the “ic”stuff: it’s for injecting custom code into the class. For that, insert a block like <xs:annotation> somewhere strategic in the XSD file. The name “ic” is not relevant: choose your own name, as long as you use it consequently.
  • xjc will generate a class named “Names”, which is named after the root element of your XML file. For the multiple Persons it generates a field in Names, being a Java List in this case.
  • Look at the field age:  see to it that the type of this element is int, not integer. That way you get a proper Java int, and not a BigInteger. Make floating point variables “double“, or else you will get also BigIntegers.
  • the <xs:all> blocks indicate, that each and every element in the all-block must be there: all persons must have a name and an age.
  • inside the <ci:code> block, you can have any valid Java code: it will be directly copied into you classes.


At the right, you find a screen dump of the NetBeans 6.9.1. project window, so you can see what all the files mean and where they go.
In the file xml_binding_build.xml, you see I added an argument to the commandline options of the compiler xjc:

<arg value="-xmlschema"/>
<arg value="-extension"/>
<arg value="-verbose"/>
<arg value="-Xinject-code"/> <!-- manually added !!! -->

This file is gereated every time you make a new XML Binding via File->New->XML Binding in Netbeans. So be aware that all changes get lost in that case. It’s awkward to have to edit this file manually, but I do not see an other option as yet.
xjc will not compile if that option is nòt present and the <ic:code>-block in the XSD file ìs there.
One day I will also find out how to use the commandline option -XtoString, so that the toString() method can more easily be incorporated and how I can avoid the problem of overwriting xml_binding_build.xml. For now, this works for me.
Tip: to find out which XJC version is in your JDK, run “xjc.exe -version” in a DOS box. XJC is in the bin folder of your JDK.

No Comments

Leave a Reply

Your email is never shared.Required fields are marked *