Adding PropertyChangeListener to AbstractButton : AbstractButton « Swing « Java Tutorial






Adding PropertyChangeListener to AbstractButton
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.JFrame;

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");
      }
    }
  }
}

public class AbstractButtonPropertyChangeListenerDemo {

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

    AbstractButton bn = new JButton("asdf");
    bn.addPropertyChangeListener(new AbstractButtonPropertyChangeListener());

    bn.setText("fdsa");

    frame.add(bn);

    frame.setSize(300, 200);
    frame.setVisible(true);
  }

}








14.4.AbstractButton
14.4.1.AbstractButton: parent class for JButtonAbstractButton: parent class for JButton
14.4.2.Supporting HTML textSupporting HTML text
14.4.3.Constants for AbstractButton PropertyChangeListener
14.4.4.Adding PropertyChangeListener to AbstractButtonAdding PropertyChangeListener to AbstractButton
14.4.5.AbstractButton Positioning