Java Beans VetoableChangeListener block focus change events

Description

Java Beans VetoableChangeListener block focus change events

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.KeyboardFocusManager;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Main {

  public static void main(final String args[]) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    KeyboardFocusManager.getCurrentKeyboardFocusManager().addVetoableChangeListener(
          new FocusVetoableChangeListener());

    frame.add(new JButton("OK"), BorderLayout.CENTER);
    frame.setSize(300, 300);/*from   w w w.  j a va2  s . c  o  m*/
    frame.setVisible(true);
  }
}

class FocusVetoableChangeListener implements VetoableChangeListener {
   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);
     }
   }
 }



PreviousNext

Related