Java Reference
In-Depth Information
7.
public class CounterFrame extends SimpleFrame {
8.
9.
public CounterFrame() {
10.
CounterPanel counterPane = new CounterPanel();
11.
this .getContentPane().add(counterPane,BorderLayout.CENTER);
12.
}
13.
}
File: its/CounterGUI/CounterDriver.java
1.
package its.CounterGUI;
2.
3.
public class CounterDriver {
public static void main(String[] args) {
4.
CounterFrame cfr = new CounterFrame();
5.
cfr.showIt("Counter");
6.
}
7.
}
8.
3.4
The counter control (listeners and events)
The link between the user actions like pressing a button and the application is es-
tablished by listeners. These are non-graphical components supplied by the AWT
library java.awt.events.* . There are different listeners for different types of
events (pressing a button, moving the mouse, etc.). Listeners are, in general, in-
terfaces not classes. We will, however, first treat listeners in much the same way
!
as classes. Experience has shown that this is much easier for inexperienced pro-
grammers to understand. Later we will describe how to make use of the interface
mechanism.
We proceed by describing how the concept of a listener works in general. Some
components of Swing can trigger events . For example a button can be pressed or
a menu item can be selected. Such events are automatically noticed by the Java
runtime system. Now, the programmer can implement a listener and assign it to
the graphical component, say a button. The listener then 'waits' until the button
is pressed and takes action if this happens. The runtime system automatically
notifies the listener if the button is pressed. The notification is done by calling
a specific method of the listener. The name of this method is predefined in the
listener's interface. The programmer must implement this method by inserting
the code that should be executed in response to the button being pressed.
In our counter application the counter has to be incremented or decremented
in response to pressing the respective button. The listener is thus assigned to both
buttons, i.e. it monitors both. If a button is pressed the listener is informed. In
order to take the appropriate action it has to know which button has been pressed.
This information is provided by the runtime system in the form of an object of type
Search WWH ::




Custom Search