19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

21 /** MyListener class */<br />

22 class MyListener implements ActionListener {<br />

23 @Override<br />

24 public void actionPerformed(ActionEvent e) {<br />

25 System.out.println("I will process it!");<br />

26 }<br />

27 }<br />

Source Component<br />

Listener Component<br />

JBut<strong>to</strong>n<br />

Generate an<br />

event<br />

Listener vec<strong>to</strong>r<br />

Process event<br />

addActionListener(ActionListener l)<br />

removeActionListener(ActionListener l)<br />

Invoke listener’s<br />

actionPerformed<br />

method<br />

MyListener class implements<br />

ActionListener<br />

actionPerformed(ActionEvent e)<br />

Test Class<br />

JBut<strong>to</strong>n jbt = new JBut<strong>to</strong>n(); // Create a source object<br />

MyListener listener = new MyListener (); // Create a listener object<br />

jbt.addActionListener(listener); // Register listener <strong>to</strong> the source<br />

Figure 36.4<br />

The listener is registered with the source, and the source invokes the<br />

listener's handler <strong>to</strong> process the event.<br />

36.5 Creating Cus<strong>to</strong>m Source Components<br />

You have used source <strong>com</strong>ponents such as JBut<strong>to</strong>n. This section<br />

demonstrates how <strong>to</strong> create a cus<strong>to</strong>m source <strong>com</strong>ponent.<br />

<br />

A source <strong>com</strong>ponent must have the appropriate registration and<br />

deregistration methods for adding and removing listeners. Events can be<br />

unicasted (only one listener object is notified of the event) or<br />

multicasted (each object in a list of listeners is notified of the<br />

event). The naming pattern for adding a unicast listener is<br />

<br />

public void addListener(Listener l)<br />

throws TooManyListenersException;<br />

The naming pattern for adding a multicast listener is the same, except<br />

that it does not throw the TooManyListenersException.<br />

<br />

public void addListener(Listener l)<br />

<br />

The naming pattern for removing a listener (either unicast or<br />

multicast) is:<br />

7

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!