ActionEvent

Google Advertisements

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

Google Advertisements

Buy This Ad Space @$20 per Month, Ad Size 600X200 Contact on: hitesh.xc@gmail.com or 8076671483

Pure VPN Privide Lowest Price VPN Just @ $1.65. Per Month with Non Detected IP Lowest Price Non Detected IP VPN

Magenet is best Adsense Alternative here we earn $2 for single link, Here we get links ads. Magenet

Download Projects

Google Advertisements


Buy Websites 9999595223

Buy Fresh and Payment Receive Media.net Account with Website. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs