ActionEvent

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 Advertisment

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

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

For Projects 9999595223

Google Advertisements


Buy Websites 9999595223

Buy College Projects with Documentation Contact on whatsapp 9999595223. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs

Advertisements