Java Swing How to - Handle Property changed event








Question

We would like to know how to handle Property changed event.

Answer

/*w  ww .  j a  v  a2s  . co  m*/
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.AbstractButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JOptionPane;

public class Main {
  public static void main(String[] args) {
    JButton bn = new JButton("asdf");
    bn.addPropertyChangeListener(new AbstractButtonPropertyChangeListener());

    bn.setText("java2s.com");

    JOptionPane.showMessageDialog(null, bn);
  }
}

class AbstractButtonPropertyChangeListener implements PropertyChangeListener {

  public void propertyChange(PropertyChangeEvent e) {
    String propertyName = e.getPropertyName();
    System.out.println("Property Name: " + propertyName);
    if (e.getPropertyName().equals(AbstractButton.TEXT_CHANGED_PROPERTY)) {
      String newText = (String) e.getNewValue();
      String oldText = (String) e.getOldValue();
      System.out.println(oldText + " changed to " + newText);
    } else if (e.getPropertyName().equals(AbstractButton.ICON_CHANGED_PROPERTY)) {
      Icon icon = (Icon) e.getNewValue();
      if (icon instanceof ImageIcon) {
        System.out.println("New icon is an image");
      }
    }
  }
}