EVENT HANDLING AND DISPATCHING.
EVENT HANDLING AND DISPATCHING.
Pressing a key or mouse button generates events. The type of events that swing components can generate whether in java.awt.event or javax.swing.event packages are of different types. Some event types are component specific.
Each event type is represented by an object that identifies the source of the event and other additional information about what specific kind of event it is and information about the state of the source before and after the event was generated. Sources of events are most commonly components or models but also different kinds of objects can generate events.
To receive notification of events, we need to register listeners with the target object . A listener is an implementation of any of the XXListener classes (where XX is an event type) defined in the java.awt.event, java.beans and javax.swing.event packages. There is at least one method defined in each interface that takes a corresponding XXEvent as parameter. Any class supporting XXEvents notification generally implements the XXListener interface and have support for registering those listeners through addXXListener methods and unregistering those listeners through removeXXLister methods. Most event targets allow any number of listeners to be registered with them. Also any listener instance can be registered to receive events for any number of event source. Usually classes that support XXEvents() provide protected fireXX() methods used for constructing event objects and sending them to the event handlers for processing.
The code below was repeated from an earlier one but with comments that emphasis some aspects of events handling.
import javax.swing.*;
import java.awt.event.*;
//implementing listeners that processes this event type
public class Property extends JPanel implements ActionListener{
JButton jButton1 = new JButton(" ");
JTextField jText;
/** Creates a new instance of Property */
public Property() {
jButton1 = new JButton("button1");
add(jButton1);
//registering instances of this class to receive this events
jButton1.addActionListener(this);
jText = new JTextField("welcome", 20);
add(jText);
}
private static void dButton(){
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Property");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Property nProp = new Property();
nProp.setOpaque(true);
frame.setContentPane(nProp);
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e){
//event handler with associated object as parameter
jText.setText(jButton1.getMaximumSize().toString());
}
public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable(){
public void run(){
dButton();
}
});
}
}
No comments:
Post a Comment