From Java Swing Dimension JFormattedTextField bite

Today, I poke around Java Swing to build up a simple data entry. One thing I wanted to do is to create a number input field so as usually I hack through the API document and found this little JFormattedTextField component. By the judge from the API point of view it is pretty easy to use. All we have to do is instantiate the component with preferred format or mask and that is pretty much about it.

numField = newJFormattedTextField(NumberFormat.getIntegerInstance());
container.add(numField);

Now, I wanted to hook an event listener to this field and retrive new value

/* this, container which implements PropertyChangeListener */
numField.addPropertyChangeListener("value", this);

So basically we got this:

numField = new JFormattedTextField(NumberFormat.getIntegerInstance());
numField.addPropertyChangeListener("value", this);
container.add(numField);

Now if you try to call .setValue(new Integer(100)) you will present with an exception java.lang.NullPointerException. After inspecting the PropertyChangeEvent class definition I believe that Java try to compare old value and new value, but we haven’t set any value before we hook up an event listener. Therefore, Java takes it liberties to raise an error in our face and that is fair enough right?

How to fix this? Well, it is simple set initial value before hook an event listener would solve the problem.

numField = new JFormattedTextField(NumberFormat.getIntegerInstance());
numField.setValue(new Integer(0)); // this line is your savier!
numField.addPropertyChangeListener("value", this);
container.add(numField);

Leave a comment