Credits

Tuesday, February 23, 2010

Java's Event Handling

Action events on Java's button are possible through their own event - handling methods.

A component must have a listener so it can execute the corresponding event methods.  Below is an example of event handling on action buttons.



[+/-] 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