//Animation of ball //Author - Sameer Panse //To ovrcome flicker effect, I have overridden update and paint methods. //Still the effect is not completely eliminated. // You can try double buffering to overcome this effect. //This code works fine but little modifications are needed. //Soon this code will be updated. /* */ import java.awt.Graphics; import java.awt.Image; import java.awt.Color; import java.awt.*; import java.awt.event.*; public class Animation extends java.applet.Applet implements Runnable, ActionListener { //Image animPics[] = new Image[10]; Image currentImg,offscreenImg,animPic; Graphics offscreen,s; Thread runner; int x,dx=226,dy=335,y; boolean dx1=true,dy1=true; Button bStart,bStop,bExit; public void init() { bStart=new Button("Start"); bStop=new Button("Stop"); bExit=new Button("End"); animPic=getImage(getCodeBase(),"Ball1.gif"); add(bStart); //add(bStop); //add(bExit); bStart.addActionListener(this); bStop.addActionListener(this); bExit.addActionListener(this); } public void start() { if(runner==null) { runner = new Thread(this); System.out.println("Hello!!!"); //runner.start(); System.out.println("After start"); } } public void stop() { runner=null; } public void run() { System.out.println("In run"); setBackground(Color.white); //repaint(); while(true) ballrun(); // System.out.println("Finished"); } void ballrun() { int sam=0,i; while(dx<537 && dy>37 && dx>=1 && dy<=340) { if(dx==536) { System.out.println("dx changed"); dx1=false; } if(dy==339) { System.out.println("dy changed"); dy1=false; } if(dx==1) { System.out.println("dx changed"); dx1=true; } if(dy==38) { System.out.println("dy changed"); dy1=true; } x=dx; y=dy; currentImg=animPic; // System.out.println("In ballrun--"+sam); repaint(); pause(5); if(dx1) dx++; else dx--; if(dy1) dy++; else dy--; sam++; } } void pause(int time) { try { Thread.sleep(time); } catch(InterruptedException e) { System.out.println("Error......"+e); } } public void update(Graphics g) { g.setColor(getBackground()); g.fillRect(1,36,598,363); g.setColor(getForeground()); paint(g); } public void paint(Graphics screen) { if(currentImg !=null) try { screen.drawLine(2,35,598,35); screen.drawRect(1,36,598,363); screen.drawImage(currentImg,x,y,this); //System.out.println("In Paint--"); //System.out.println("currentImg--"+currentImg); } catch(InternalError e1) { System.out.println("Error "+e1); } } public void actionPerformed(ActionEvent e) { if(e.getSource()==bStart) { showStatus("Animation Started"); runner.start(); } /* if(e.getSource()==bStop) { showStatus("Animation Stoped"); runner=null; } if(e.getSource()==bExit) { showStatus("Animation Ends"); }*/ } }