I am trying to get a simple program to work were a image moves across the window. When my program gets to the void hop(int iStart, int iStop) method, repaint does not invoke a new paint. So all I get is a blank screen. How can I get repaint to place my image in the window?
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Main extends Applet implements ActionListener{
Animate animate;
Button fire;
public void init()
{
this.setBackground(Color.white);
fire = new Button("Fire!");
add(fire);
fire.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent arg0) {
animate = new Animate();
}
}
//*******************************************
import java.awt.*;
import java.io.*;
import javax.imageio.*;
public class Animate extends Panel implements Runnable{
Thread threadBananaAnimation = new Thread(this);
Image img;
int xPosition = 0;
int yPosition = 50;
int iStart = 0;
int iStop = 300;
public Animate()
{
try
{
File file = new File("c:/banana.gif");
img = ImageIO.read(file);
}catch (Exception e)
{
System.out.print("Could not find image file!");
}
threadBananaAnimation.start();
}
public void run()
{
while (true)
{
hop( 0, 300);
repaint();
try { Thread.sleep( 500 ); }
catch (InterruptedException e) { }
hop( 300, 600);
hop( 600, 300);
repaint();
try { Thread.sleep( 500 ); }
catch (InterruptedException e) { };
hop( 300, 0);
}
}
void hop(int iStart, int iStop)
{
boolean bGround = true;
System.out.print("This is a test");
//*****The program is running through this for loop
//*****but will not repaint my image
for (int i = iStart; i < iStop; i += 10)
{
xPosition = Math.abs(i);
if (bGround)
{
yPosition = 50;
bGround = false;
}
else
{
yPosition = 40;
bGround = true;
}
try { Thread.sleep( 500 ); }
catch (InterruptedException e) { }
repaint();
}
}
public void paintComponent(Graphics g)
{
super.paintComponents(g);
g.drawImage(img, xPosition, yPosition, getParent());
}
}
Thanks in advance for your help!!