As others pointed out, you made a typo in the paintComponent
method's name. The second problem is you'll get a NullpointerException
due to line currentFrame = 0;
(after the first iteration) as you started filling the imageArray from index 1.
There's nothing wrong with the getResource
part of your code, as it would've have thrown an exception on that line if no image was to be found.
Advice:
Use the Override
annotation when overriding a superclass' method. The compiler will start complaining about the annotation's incorrect use in case you made a typo.
This answer isn't necessarily indicative of how to do things. But it does make your code work:
import javax.swing.*;
import javax.swing.JFrame;
import java.awt.event.*;
public class Main extends JPanel implements ActionListener {
private final Timer animate;
private final ImageIcon imageArray[];
private int delay = 50, frameCount = 200, currentFrame = 0;
public Main() {
imageArray = new ImageIcon[frameCount];
for (int i = 1; i < imageArray.length; i++) {
imageArray[i] = new ImageIcon(getClass().getResource("Cartest (" + i + ").jpg"));
}
animate = new Timer(delay, this);
animate.start();
}
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
@Override
public void paintComponent(Graphics g) {
currentFrame++;
if (currentFrame == imageArray.length) {
currentFrame = 1;
}
imageArray[currentFrame].paintIcon(this, g, 0, 0);
}
public static void main (String args[]) {
JFrame f= new JFrame("hello");
Main s = new Main();
f.add(s);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400,400);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…