473,671 Members | 2,384 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Would Like to See Examples of Listeners

I've said here before that I'm self taught. I have 4 reference books, and
they mention listeners and give partial examples, but not one gives me a
good, clear example of setting up a listener, using it, and disposing it.

Can anyone either point me to some good examples online, or show me one? It
would save me a day or two of try different ways to do it.

Thanks for any help.

Hal
Jul 17 '05 #1
4 3002
On Thu, 07 Aug 2003 22:39:01 GMT, Hal Vaughan <ha*@thresholdd igital.com>
two-finger typed:
I've said here before that I'm self taught. I have 4 reference books, and
they mention listeners and give partial examples, but not one gives me a
good, clear example of setting up a listener, using it, and disposing it.

Can anyone either point me to some good examples online, or show me one?It
would save me a day or two of try different ways to do it.

Thanks for any help.

Hal

A listener is basically a class that implements the method or methods
described in the listener interface, such as java.awt.event. ActionListener.

I. using a listener

Just add the listener implemenation to an 'event' source:
myButton.addAct ionListener(myL istener);

II. disposing of a listener

Just remove the listener implemenation from the 'event' source:
myButton.remove ActionListener( myListener);

III. creating a listener

You can do this in three different ways:
1) make one of your public classes implement the listener itself.
2) create an anonymous inner class that creates the listener.
3) create a named inner class that implements the listener.

1: Example1Class.j ava

import java.awt.* ;
import java.awt.event. * ;

// Advantages:
// - no complex code
// - external classes can issue the command
// (accessibility e.g. by using Example1Class.C OMMAND)
// - listener can be removed again (disable method in this case).
// - single class file implementation.
//
// Disadvantage:
// - events can be spoofed (made look like they are authentic
// and come from myButton without user interaction).
public Example1Class implements ActionListener {
public final static String COMMAND = "CLICKED";
Button myButton = new Button("Click here");
public Example1Class(C ontainer parent) {
super();
myButton.setAct ionCommand(COMM AND);
myButton.setBou nds(10,10,200,2 0);
parent.add(myBu tton);
}
public void enable() {
myButton.addAct ionListener(thi s);
}
public void disable() {
myButton.remove ActionListener( this);
}
public void actionPerformed (ActionEvent event) {
Object source = event.getSource ();
String action = event.getAction Command();
System.out.prin tln(
"Action issued from "+source.toStri ng());
System.out.prin tln("Command: "+action);
}
}

2: Example2Class.j ava

import java.awt.* ;
import java.awt.event. * ;

// Advantages:
// - no complex code
// - information hiding, security (no spoofing):
// only the button can/will issue the events.
//
// Disadvantages:
// - listener cannot be removed easily, since no reference exists
// (except in the button itself).
// - two class files to distribute (one with added $1 in the name)

public Example2Class {
Button myButton = new Button("Click here");
public Example2Class(C ontainer parent) {
super();
myButton.setAct ionCommand("CLI CKED");
myButton.setBou nds(10,10,200,2 0);
parent.add(myBu tton);
}
public void enable() {
myButton.addAct ionListener(new ActionListener(
{
public void actionPerformed (ActionEvent event) {
Object source = event.getSource ();
String action = event.getAction Command();
System.out.prin tln(
"Action issued from "+source.toStri ng());
System.out.prin tln("Command: "+action);
}
});
}
}

3: Example3Class.j ava

import java.awt.* ;
import java.awt.event. * ;

// Advantages:
// - information hiding, security (no spoofing):
// only the button can/will issue the events.
// - listener can be removed again (disable method in this case).
//
// Disadvantages:
// - more complex code
// - two class files to distribute (one with added $Respond)

public Example3Class {
Button myButton = new Button("Click here");
public Example2Class(C ontainer parent) {
super();
myButton.setAct ionCommand("CLI CKED");
myButton.setBou nds(10,10,200,2 0);
parent.add(myBu tton);
}
class Respond {
public void actionPerformed (ActionEvent event) {
Object source = event.getSource ();
String action = event.getAction Command();
System.out.prin tln(
"Action issued from "+source.toStri ng());
System.out.prin tln("Command: "+action);
}
} responder = new Respond();

public void enable() {
myButton.addAct ionListener(res ponder);
}
public void disable() {
myButton.remove ActionListener( responder);
}
}
Have fun,
Cheers.
Jul 17 '05 #2
Hal Vaughan <ha*@thresholdd igital.com> wrote in message news:<8yAYa.603 41$cF.20558@rwc rnsc53>...
I've said here before that I'm self taught. I have 4 reference books, and
they mention listeners and give partial examples, but not one gives me a
good, clear example of setting up a listener, using it, and disposing it.
What do you mean by 'partial' ?

You're unlikely to find a tutorial or examples which focus specifically
on listeners, as they are merely the mechanics which enable events to be
delivered from one part of a Java application to another, and as such
they tend to be taught as part of something bigger (usually AWT/Swing!)
rather than as an isolated topic in their own right.

Can anyone either point me to some good examples online, or show me one? It
would save me a day or two of try different ways to do it.


There's nothing magically about listeners. A given piece of Java code
which may be required to signal events to other parts of an application
(for example, a button when it is clicked) will provide the facility to
remember one or more listeners, who are interested in receiving notifi-
cation of its events. The interested parties are responsible for
registering themselves with the event source, so the source knows of
their existance and can dispatch events to them, as and when...

The actual coupling between event source and listener is typically done
in the form of an interface, which each interested party implements, to
provide methods which the event source can then call to signal that a
given event has occured - typically passing over an event object which
contains specific details of the event.

There are certain naming patterns (conventions) which apply. They are
not mandatory, but they do make the code more readable. Each set of
events is known by a given name, and that name is then used as the
basis of the various classes, interfaces and methods which define the
listener mechanism for that set of events.

As some listeners handle several events (several event methods) you'll
also find 'adapter' classes are often available to help minimise the
amount of coding needed to implement a listener. Adapters provide a
default implementation of an interface (typically not doing anything
useful with the events) allowing the programmer to override only those
event handling methods she is interested in - rather than providing
code for *every* method in the listener interface. You'll usually find
that adapters are build using inner classes of the class which is actua-
lly interested in the event - but they don't *have* to be!
-FISH- ><>
Jul 17 '05 #3
Wow!

I've been wading through my books, the web, the OpenOffice.org idl ref and
the Java SDK references. You did a great job at simplifying everything and
making it quite clear. I didn't realize it was so simple.

Hal

Neomorph wrote:
On Thu, 07 Aug 2003 22:39:01 GMT, Hal Vaughan <ha*@thresholdd igital.com>
two-finger typed:
I've said here before that I'm self taught. I have 4 reference books, and
they mention listeners and give partial examples, but not one gives me a
good, clear example of setting up a listener, using it, and disposing it.

Can anyone either point me to some good examples online, or show me one?
It would save me a day or two of try different ways to do it.

Thanks for any help.

Hal

A listener is basically a class that implements the method or methods
described in the listener interface, such as
java.awt.event. ActionListener.

I. using a listener

Just add the listener implemenation to an 'event' source:
myButton.addAct ionListener(myL istener);

II. disposing of a listener

Just remove the listener implemenation from the 'event' source:
myButton.remove ActionListener( myListener);

III. creating a listener

You can do this in three different ways:
1) make one of your public classes implement the listener itself.
2) create an anonymous inner class that creates the listener.
3) create a named inner class that implements the listener.

1: Example1Class.j ava

import java.awt.* ;
import java.awt.event. * ;

// Advantages:
// - no complex code
// - external classes can issue the command
// (accessibility e.g. by using Example1Class.C OMMAND)
// - listener can be removed again (disable method in this case).
// - single class file implementation.
//
// Disadvantage:
// - events can be spoofed (made look like they are authentic
// and come from myButton without user interaction).
public Example1Class implements ActionListener {
public final static String COMMAND = "CLICKED";
Button myButton = new Button("Click here");
public Example1Class(C ontainer parent) {
super();
myButton.setAct ionCommand(COMM AND);
myButton.setBou nds(10,10,200,2 0);
parent.add(myBu tton);
}
public void enable() {
myButton.addAct ionListener(thi s);
}
public void disable() {
myButton.remove ActionListener( this);
}
public void actionPerformed (ActionEvent event) {
Object source = event.getSource ();
String action = event.getAction Command();
System.out.prin tln(
"Action issued from "+source.toStri ng());
System.out.prin tln("Command: "+action);
}
}

2: Example2Class.j ava

import java.awt.* ;
import java.awt.event. * ;

// Advantages:
// - no complex code
// - information hiding, security (no spoofing):
// only the button can/will issue the events.
//
// Disadvantages:
// - listener cannot be removed easily, since no reference exists
// (except in the button itself).
// - two class files to distribute (one with added $1 in the name)

public Example2Class {
Button myButton = new Button("Click here");
public Example2Class(C ontainer parent) {
super();
myButton.setAct ionCommand("CLI CKED");
myButton.setBou nds(10,10,200,2 0);
parent.add(myBu tton);
}
public void enable() {
myButton.addAct ionListener(new ActionListener(
{
public void actionPerformed (ActionEvent event) {
Object source = event.getSource ();
String action = event.getAction Command();
System.out.prin tln(
"Action issued from "+source.toStri ng());
System.out.prin tln("Command: "+action);
}
});
}
}

3: Example3Class.j ava

import java.awt.* ;
import java.awt.event. * ;

// Advantages:
// - information hiding, security (no spoofing):
// only the button can/will issue the events.
// - listener can be removed again (disable method in this case).
//
// Disadvantages:
// - more complex code
// - two class files to distribute (one with added $Respond)

public Example3Class {
Button myButton = new Button("Click here");
public Example2Class(C ontainer parent) {
super();
myButton.setAct ionCommand("CLI CKED");
myButton.setBou nds(10,10,200,2 0);
parent.add(myBu tton);
}
class Respond {
public void actionPerformed (ActionEvent event) {
Object source = event.getSource ();
String action = event.getAction Command();
System.out.prin tln(
"Action issued from "+source.toStri ng());
System.out.prin tln("Command: "+action);
}
} responder = new Respond();

public void enable() {
myButton.addAct ionListener(res ponder);
}
public void disable() {
myButton.remove ActionListener( responder);
}
}
Have fun,
Cheers.


Jul 17 '05 #4
FISH wrote:
Hal Vaughan <ha*@thresholdd igital.com> wrote in message
news:<8yAYa.603 41$cF.20558@rwc rnsc53>...
I've said here before that I'm self taught. I have 4 reference books,
and they mention listeners and give partial examples, but not one gives
me a good, clear example of setting up a listener, using it, and
disposing it.
What do you mean by 'partial' ?

You're unlikely to find a tutorial or examples which focus specifically
on listeners, as they are merely the mechanics which enable events to be
delivered from one part of a Java application to another, and as such
they tend to be taught as part of something bigger (usually AWT/Swing!)
rather than as an isolated topic in their own right.

Can anyone either point me to some good examples online, or show me one?
It would save me a day or two of try different ways to do it.


There's nothing magically about listeners. A given piece of Java code
which may be required to signal events to other parts of an application
(for example, a button when it is clicked) will provide the facility to
remember one or more listeners, who are interested in receiving notifi-
cation of its events. The interested parties are responsible for
registering themselves with the event source, so the source knows of
their existance and can dispatch events to them, as and when...


That's what it took me time to figure out. I found so little on them, it
seemed like there was something going on that I was missing. It took me a
few days of poking around to finally get one working correctly.
The actual coupling between event source and listener is typically done
in the form of an interface, which each interested party implements, to
provide methods which the event source can then call to signal that a
given event has occured - typically passing over an event object which
contains specific details of the event.

There are certain naming patterns (conventions) which apply. They are
not mandatory, but they do make the code more readable. Each set of
events is known by a given name, and that name is then used as the
basis of the various classes, interfaces and methods which define the
listener mechanism for that set of events.

As some listeners handle several events (several event methods) you'll
also find 'adapter' classes are often available to help minimise the
amount of coding needed to implement a listener. Adapters provide a
default implementation of an interface (typically not doing anything
useful with the events) allowing the programmer to override only those
event handling methods she is interested in - rather than providing
code for *every* method in the listener interface. You'll usually find
that adapters are build using inner classes of the class which is actua-
lly interested in the event - but they don't *have* to be!
Actually, I found more on "adapter" classes than on just listeners.
Thanks!

Hal
-FISH- ><>


Jul 17 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1416
by: mathon | last post by:
Hello, could anybody explain me the advantages and disadvantages of delegation and the advantages and disadvantages using event-listeners? - both related to the treatment of events. thanks in advance regards
1
2416
by: pokémon | last post by:
Ok, I am baffled by this one: I have 2 custom trace listeners (classes that inherit from System.Diagnostics.TraceListener). I want them both to listen to the same Windows application. How should I go about doing this? Do they need to be in the same AppDomain? Do I need to create an AppDomain? I put the both in the <listeners> App.Config section for the app I want them
1
1852
by: Fred Mellender | last post by:
When I code: Debug.Assert(false, "this is a message"); it works fine, and out comes the dialog box. When I code Trace.Listeners.Clear(); Debug.Assert(false, "this is a message"); No message is output. In the debugger I see that clearing the Trace Listeners clears the Debug
2
1725
by: Michael Powe | last post by:
Hello, Is there a way (in JS) to detect listeners on an element and identify them? The purpose would be to selectively attach additional listeners if certain conditions are met. For example, I want to attach listenerA to links that go to PDFs and listenerB to links that go off site. But, I don't want both A and B attached to offsite links that point to PDFs. I would like to be able to choose which to attach, so that
0
1645
by: msnews.microsoft.com | last post by:
Hi, I am tring to use Trace Listener in asp.net 1.1 application as mentoned here. But i am getting the following error, Configuration Error Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately. Parser Error Message: Exception in configuration section handler.
1
1543
by: Armin Zingler | last post by:
Hi, I add a TraceListener to Debug.Listeners. After that I use Debug.writeline. Problem: Nothing arrives at the listener. Code: Dim ts As New TraceStream Debug.Listeners.Add(New TextWriterTraceListener(ts))
6
3952
by: Zytan | last post by:
According to http://www.15seconds.com/issue/020910.htm I am doing this in the c'tor of a 'logfile' class: objStream = new System.IO.FileStream(logFilename, System.IO.FileMode.OpenOrCreate); objTraceListener = new TextWriterTraceListener(objStream); Trace.Listeners.Add(objTraceListener); So, now all Debug.Write and Trace.Write get logged to the file. In the d'tor I am doing:
0
8924
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8823
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8602
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8672
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5702
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4227
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4412
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2058
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1814
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.