Bu örnekte bir resim bir canvas içinde hareket etmektedir. Canvas'ın kenarlarına çarpıp geri dönmektedir.
1 import javax.swing.*;
2 import java.awt.*;
3 public class ImageMove extends JFrame{
4 public ImageMove(){
5 setBounds(10,10,100,100);
6 String path="E:\\Test\\room.png";
7 Image image=Toolkit.getDefaultToolkit().createImage(path);
8 Canvas c=new Canvas();
9 c.setBackground(Color.WHITE);
10 Hero hero=new Hero(image,c);
11 getContentPane().setLayout(new BorderLayout());
12 getContentPane().add(c);
13 setVisible(true);
14 }
15 public static void main(String[] args) {
16 new ImageMove();
17 }
18 }
Hareket eden resim için Hero class'ı yaartılmıştır. Bu class ile resim canvas'ın kenralarına çarpıp geri dönmektedir.
1 import java.awt.*;
2 import java.util.*;
3 public class Hero{
4 private Image image;
5 private Canvas canvas;
6 private int deltaX=1,deltaY=1;
7 private int x,y;
8 public Hero(Image img,Canvas c){
9 image=img;
10 canvas=c;
11 Timer timer=new Timer();
12 TimerTask task=new TimerTask(){
13 public void run(){
14 move();
15 }
16 };
17 timer.schedule(task,new Date(),100);
18 }
19 private void move(){
20 x+=deltaX;
21 y+=deltaY;
22 if(hasInside()){
23 draw();
24 }else{
25 nextDirection();
26 }
27 }
28 private void draw(){
29 Graphics g=canvas.getGraphics();
30 g.setColor(Color.WHITE);
31 g.fillRect(0,0,getCanvasWidth(),getCanvasHeight());
32 g.drawImage(image,x,y,canvas);
33 }
34 private void nextDirection(){
35 if(x<0){
36 deltaX=1;
37 }else if(y<0){
38 deltaY=1;
39 }else if(x>getCanvasWidth()-getWidth()){
40 deltaX=-1;
41 }else if(y>getCanvasHeight()-getHeight()){
42 deltaY=-1;
43 }
44 }
45 private boolean hasInside(){
46 return getCanvasBounds().contains(getBounds());
47 }
48 private int getWidth(){
49 return (int)getBounds().getWidth();
50 }
51 private int getHeight(){
52 return (int)getBounds().getHeight();
53 }
54 private Rectangle getBounds(){
55 return new Rectangle(x,y,image.getWidth(canvas),image.getHeight(canvas));
56 }
57 private int getCanvasWidth(){
58 return (int)getCanvasBounds().getWidth();
59 }
60 private int getCanvasHeight(){
61 return (int)getCanvasBounds().getHeight();
62 }
63 private Rectangle getCanvasBounds(){
64 return canvas.getBounds();
65 }
66 }