Credits

Monday, February 15, 2010

Java's Action Event and Listener

If buttons are clicked and  we expect to have some actions, then we associate an action event on these components. 


To integrate events for buttons, we associate ActionEvent and ActionListener to respond to events.

[+/-] show/hide




import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ButtonActionEventv2 extends JFrame implements ActionListener
{
JButton redButton = new JButton("Red");
JButton greenButton = new JButton("Green");
JButton blueButton = new JButton("Blue");
JPanel pane=new JPanel();
public ButtonActionEventv2(){
    
setTitle("Button Action Event Frame");
setSize(300,150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
redButton.addActionListener(this);
pane.add(redButton);

greenButton.addActionListener(this);
pane.add(greenButton);
blueButton.addActionListener(this);
pane.add(blueButton);
add(pane);
setVisible(true);
}

public void actionPerformed(ActionEvent e){
Object source = e.getSource();
if (source==redButton)
pane.setBackground(Color.red);
else if (source==greenButton)
pane.setBackground(Color.green);
else pane.setBackground(Color.blue);

}

public static void main (String[] args){
ButtonActionEventv2 apps = new ButtonActionEventv2();

}
}

AddThis