VetoableChangeListener example
With this example you are going to learn about a very important event monitoring component, the VetoableChangeListener
. The VetoableChangeListener
is , in many ways, similar to the PropertyChangeListener
class. The main difference is that PropertyChangeListener
is applied to bound properties. On the other hand the VetoableChangeListener
is applied to constraint properties.
A bound property is just as simple as a property. A constraint property is a property that can change its state only if the event listener allows it to. For example, if the new value of the property is bigger that the listener can allow, it can refuse to give the new value to the property.
In order to work with a VetoableChangeListener
one should take the following steps:
- Use the
addVetoableChangeListener
method of an event manager and give the new class as an argument to bundle an event with aVetoableChangeListener.
- Create a new class that implements the
VetoableChangeListener
interface. Override thevetoableChange
method and examine the old and the new value of the property. If you are not happy with the new value you can throw aPropertyVetoException
Let’s take a look a the code:
package com.javacodegeeks.snippets.desktop; import java.awt.Component; import java.awt.KeyboardFocusManager; import java.beans.PropertyChangeEvent; import java.beans.PropertyVetoException; import java.beans.VetoableChangeListener; public class VetoableChangeListenerExample { public static void main(String[] argv) { KeyboardFocusManager.getCurrentKeyboardFocusManager().addVetoableChangeListener( new FocusVetoableChangeListener()); } } class FocusVetoableChangeListener implements VetoableChangeListener { @Override public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException { Component oldComp = (Component) evt.getOldValue(); Component newComp = (Component) evt.getNewValue(); if ("focusOwner".equals(evt.getPropertyName())) { if (oldComp == null) { System.out.println(newComp.getName()); } else { System.out.println(oldComp.getName()); } } else if ("focusedWindow".equals(evt.getPropertyName())) { if (oldComp == null) { System.out.println(newComp.getName()); } else { System.out.println(oldComp.getName()); } } boolean vetoFocusChange = false; if (vetoFocusChange) { throw new PropertyVetoException("message", evt); } } }
This was an example on how to use VetoableChangeListener
.