principlejavaMinor
Is this the correct approach to animation in Java?
Viewed 0 times
thisanimationthejavacorrectapproach
Problem
I was fiddling with animation in Java and wrote this:
Is this the correct approach or is this just bad practice?
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.Timer;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
class Main extends JFrame implements ActionListener {
private Timer timer = new Timer(500, this);
private Image mario1 = new ImageIcon("C:/Users/User/workspace/Game Development/src/mario.jpg").getImage();
private Image mario2 = new ImageIcon("C:/Users/User/workspace/Game Development/src/mario2.jpg").getImage();
private int counter = 0;
private ArrayList scenes = new ArrayList();
public Main() {
setSize(500, 500);
setVisible(true);
addScene(mario1);
addScene(mario2);
timer.start();
}
public void actionPerformed(ActionEvent e) {
nextScene();
}
public void addScene(Image image) {
scenes.add(image);
}
public void nextScene() {
counter++;
repaint();
}
@Override
public void paint(Graphics g) {
super.paint(g);
if (!(counter = scenes.size())) g.drawImage(scenes.get(counter), 100, 100, null);
}
public static void main(String[] args) {
new Main();
}
}Is this the correct approach or is this just bad practice?
Solution
Two recommendations:
-
rather than testing on
Also, declare your list as a
- It is better that you don't "do any action" in the constructor; create, say, a
.start()method and donew Main().start()inmain();
-
rather than testing on
count in animation, use this, where nrImages is the number of images:count = (count + 1) % nrImages;Also, declare your list as a
List, not an ArrayList: use interfaces when available.Code Snippets
count = (count + 1) % nrImages;Context
StackExchange Code Review Q#26720, answer score: 2
Revisions (0)
No revisions yet.