Friday, August 9, 2013

ActionListener

ActionListener is an interface to receive action event that is generated by a source component. Some Components that can generate action event are Button, List, and MenuItem (awt) or JButton, JList, and JMenuItem (swing). The action event occurs when the button is pushed or when an item of the menu is clicked or an item of the list is double-clicked.

To receive the action event and perform action, the application must implement the ActionListener interface and register the listener with the source component by using its addActionListener(ActionListener listener) method. Then override the actionPerformed(ActionEvent e) method.

Example:
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Canvas;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

class ImageBox extends Canvas{
double sx;
double sy;
BufferedImage bi;
ImageBox(){
sx=1;
sy=1;
try{
bi=ImageIO.read(new File("d:/earth2.jpg"));
}catch(IOException e){}

}
public void paint(Graphics g){

Graphics2D g2d=(Graphics2D)g;
g2d.translate(300-bi.getWidth()/2,200-bi.getHeight()/2);
g2d.scale(sx,sy);
g2d.drawImage(bi,0,0,null);

}

public void changeFactors(String command){
if(command.equals("+")){
sx+=0.1;
sy+=0.1;
}
else{
sx-=0.1;
sy-=0.1;
}

repaint();



}
}
class Display extends Frame{
ImageBox ib;
Display(){
setTitle("ActionListener");
setVisible(true);
setSize(600,500);
setLayout(new BorderLayout());
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});

Button btzoomin=new Button("+");
btzoomin.addActionListener(new ActionList());
Button btzoomout=new Button("-");
btzoomout.addActionListener(new ActionList());
Panel p=new Panel();
p.add(btzoomin);
p.add(btzoomout);
add(p,BorderLayout.NORTH);
ib=new ImageBox();
add(ib,BorderLayout.CENTER);
validate();

}

class ActionList implements ActionListener{
public void actionPerformed(ActionEvent e){
ib.changeFactors(e.getActionCommand());


}
}

}
public class ActionListenerTest {
public static void main(String[] args){
new Display();
}
}

actionlistener actionevent

No comments:

Post a Comment