Læs mere om Sådan bruges svingtimere
Her er prøvekoden:
int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//...Perform a task...
}
};
new Timer(delay, taskPerformer).start();
Find en Eksempelkode her
Eksempelkode:(Flyt et billede 1px vandret fra venstre mod højre med et interval på 200 ms )
private int x = 1;
...
final Image image = ImageIO.read(new File("resources/1.png"));
final JPanel panel = new JPanel() {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image,x,10,null);
}
};
int delay = 200; // milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
x++;
if (x > 100) {
x = 1;
}
panel.repaint();
}
};
new Timer(delay, taskPerformer).start();