Original Post
Hi, I've been asked to make a program with two buttons. One that sais "Left" and the other that sais "Right". An object will the move from the left to right position or the other way around. The only problem is that I'm not allowed to use threads. Normally I'd use multithreading for animation, but he wants it as simple as possible, so, no threads. This is what I came up with: The problem is that the object does move at the specified speed and such, so it works fine, but during the animation the screen isn't repainted. I think I'm bashing the system to hard with the loop so there is no time for updates. As far as I see, there are two possibities now: - Use a timer. Is there a timer available in Java? - Find a way to update the screen during the animation. Do you know any? Oh, this is not for homework, altough it is a teacher who asked me. I guess he needs it as an example for other students. I've already made some solid stuff in Java, but that was fully object oriented and multithreaded all (for the animation). Thanks!
package hendel;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class hendel extends Applet
{
int hendelpos = 150; // between 50 and 250;
Button links = new Button("Links");
Button rechts = new Button("Rechts");
public void init()
{
setLayout(null);
links.setBounds(50, 150, 75, 25);
links.addActionListener(new LinksHandler());
add(links);
rechts.setBounds(175, 150, 75, 25);
rechts.addActionListener(new RechtsHandler());
add(rechts);
repaint();
}
public void paint(Graphics g)
{
g.setColor(Color.lightGray);
g.fillRect(0, 0, 300, 200);
g.setColor(Color.black);
g.fillRect(hendelpos-5, 45, 10, 10);
}
class LinksHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
while(hendelpos>50)
{
try { Thread.sleep(20); } catch(InterruptedException ie) {}
hendelpos -= 5;
repaint();
}
}
}
class RechtsHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
while(hendelpos<250)
{
try { Thread.sleep(20); } catch(InterruptedException ie) {}
hendelpos += 5;
repaint();
}
}
}
}