import java.awt.BorderLayout;
import javax.swing.JFrame;
public class EventSourceTest {
/**
* @param args
*/
public static void main(String[] args) {
EventSourceFrame frame = new EventSourceFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JFrame;
class EventSourceFrame extends JFrame {
public static final int DEFAULT_WITH = 400;
public static final int DEFAULT_HEIGHT = 200;
public EventSourceFrame() {
setTitle("EventSourceTest");
setSize(DEFAULT_WITH, DEFAULT_HEIGHT);
final PaintCountPanel panel = new PaintCountPanel();
add(panel);
panel.addPropertyChangeListener(new
PropertyChangeListener()
{
public void propertyChange(PropertyChangeEvent event){
setTitle("java核心技术简单例子"+event.getNewValue());
}
});
}
}
import java.awt.Graphics;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.EventListener;
import javax.swing.JPanel;
class PaintCountPanel extends JPanel {
public void paintComponent(Graphics g) {
int oldPaintCount = paintCount;
paintCount++;
firePropertyChangeEvent(new PropertyChangeEvent(this, "paintCount",oldPaintCount,
paintCount));
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
listenerList.add(PropertyChangeListener.class, listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
listenerList.remove(PropertyChangeListener.class, listener);
}
public void firePropertyChangeEvent(PropertyChangeEvent event) {
EventListener[] listeners = listenerList
.getListeners(PropertyChangeListener.class);
for (EventListener l : listeners)
((PropertyChangeListener)l).propertyChange(event);
}
public int getPaintCoutn() {
return paintCount;
}
private int paintCount;
}