I have a 2 JFormattedTextFields that input the same information in different forms. I want to have one change when the user change the other. I have implemented something like this before using PropertyChangeListeners, however I have encountered a strange error this time.
When my JFrame opens the PropertyChangeListener event is fired for no apparent reason. The value of getNewValue() on the PropertyChangeEvent is null.
Here is all the code that references my label:
private JFormattedTextField fpsField;
Then later in my JFrame constructor:
fpsField = new JFormattedTextField(NumberFormat.getInstance());
fpsField.addPropertyChangeListener("value", new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent arg0) {
if(!updatingFPS){
updatingFPS = true;
Float fps = (Float) arg0.getNewValue();
long newDelay = Math.round(1000/fps);
delayField.setValue(newDelay);
updatingFPS = false;
}
}
});
GridBagConstraints gbc_fpsField = new GridBagConstraints();
gbc_fpsField.insets = new Insets(0, 0, 5, 0);
gbc_fpsField.fill = GridBagConstraints.HORIZONTAL;
gbc_fpsField.gridx = 1;
gbc_fpsField.gridy = 0;
monitorPreferencesPane.add(fpsField, gbc_fpsField);
fpsField.setColumns(10);
As you can see I do not set the value in code and the event is called (and generates a NullPointerException) before I get a chance to type anything in. I have not written the listener for delayField yet.
Since the default value is
null, the focus event fired when opening theJFramewill fire a property change event becausenullcan not be adequately compared. See the full explanation with code below after the possible solutions.One solution to get rid of the NPE is to set a default value to your
fpsFieldbefore adding thePropertyChangeListenersince doing that will not fire thePropertyChangeevent when theJFrameopens.Another solution, if you can't set the default value, is to check if the old and new values in the event are actually different before updating your
delayField. They are bothnullwhen theJFrameopens.The reason the event is fired is because a
FocusEvent, where the cause isACTIVATIONis fired and processed by yourJFormattedTextField, which callsand
since
firePCistrue, it fires thePropertyChangeevent onvalue.Finally, since the default value is
null, the condition to actually fire the eventwill fire it,
oldValueandnewValuebeing bothnull.