Mega Code Archive

 
Categories / Java Tutorial / Swing
 

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