ActionEvent
Advertisements
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 Component | Event class | Listener Interface | Method (abstract method) |
---|---|---|---|
Button | ActionEvent | ActionListener | public 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
In above example when you click on button then change background color of frame.
Google Advertisment