ActionEvent


Prev Tutorial Next Tutorial

Event Handling for Button

Event handling for button component you need to use ActionEvent class and ActionListener interface.

ActionEvent class and ActionListener interface is associated with button component. If any button is clicked operation will be performed by writing the logic in actionPerform().

GUI ComponentEvent classListener InterfaceMethod (abstract method)
ButtonActionEventActionListenerpublic void actionPerformed(ActionEvent e)

Example of ActionEvent

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

class A implements ActionListener
{
Frame f;
Button b1,b2,b3,b4;
A()
{
 f=new Frame();
 f.setSize(500,500);
 f.setLayout(new BorderLayout());
 Panel p=new Panel();
 p.setBackground(Color.cyan);
 b1=new Button("Red");
 b2=new Button("green");
 b3=new Button("Blue");
 b4=new Button("Exit");
 p.add(b1);
 p.add(b2);
 p.add(b3);
 p.add(b4);
 f.add("North",p);
 b1.addActionListener(this);
 b2.addActionListener(this);
 b3.addActionListener(this);
 b4.addActionListener(this);
 f.setVisible(true);
}

public void actionPerformed(ActionEvent e)
{
try
{
if(e.getSource().equals(b1))
{
f.setBackground(Color.red);
}
else if(e.getSource().equals(b2))
{
f.setBackground(Color.green);
}
else if(e.getSource().equals(b3))
{
f.setBackground(Color.blue);
}
else if(e.getSource().equals(b4))
{
System.exit(0);
}
}
catch (Exception ec)
{
System.out.println(ec);
}
}
};

class ActionEventEx
{
public static void main(String[] args) 
{
A a1=new A();
}
}

Download code Click

actionevent example

In above example when you click on button then change background color of frame.


Prev Tutorial Next Tutorial

Advertisements




Facebook Likes

Advertisements