Common events are residing in java.awt.event package and javax.swing.event
package.
Basically all events are Interface types so there is only method
declaration, & allows you to inherit as many as Interface if u want.
While using these interfaces you have to override the method already
declared in parent interface and put some of your code here to do some action.
Basically java SWING / AWT are using this Event Driven Model, simply user
has to Click / Enter something to do some action.
Some common properties for Events in Java
1. All Event Listeners are Interface & having public, void signatures,
so NO event will return something to user.
3. You can use Adapter classes if u dont want to override all the
methods of a Interface, in my example I have used WindowAdapter class &
Overridden only windowClosing() method, simply Event Adapter will put null body
on the methods which u r not overridden
4. Interface methods have EventObject as parameter which will give
additional info about this Event, like getSource(), getX(),getY()
5. You can remove a listener to the component using
remove<ListenerName>() methods
if I am wrong on something here plz let me know
example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ActionDemo extends JFrame implements ActionListener
{
JButton jbtnDemo = new JButton("Click Here");
public ActionDemo()
{
super("Action Listener Demo");
setSize(150,100);
Container c = getContentPane();
c.setLayout(new FlowLayout(FlowLayout.CENTER));
c.add(jbtnDemo);
validate();
pack();
show();
jbtnDemo.addActionListener(this); //this will add the listener to
this button so that if any body clicks this button the actionPerformed() method
will be fired
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
dispose();
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() == jbtnDemo)
{
JOptionPane.showMessageDialog(this,"You have clicked on me
:)","Click Here",JOptionPane.INFORMATION_MESSAGE);
}
}
public static void main(String args[])
{
new ActionDemo();
}
}