【发布时间】:2013-07-12 19:23:54
【问题描述】:
如何根据计时器移动图像?我试图让图像移动没有任何用户输入,但我做错了,因为我无法移动图像。
我是否错误地调用了我为实际移动图像而构建的方法AnimationPanel?我觉得这与此有关。
这是我迄今为止尝试过的:重载的构造函数是为了让我可以从这个特定的类中轻松调用AnimationPanel。
public class ClassC extends Component {
int x; int y;
BufferedImage img;
public void paint(Graphics g) {
g.drawImage(img, x, y, null);
}
public ClassC() {
try {
img = ImageIO.read(new File("RobotFrame1.png"));
} catch (IOException e) {
}
}
public ClassC(int x)
{}
public Dimension getPreferredSize() {
if (img == null) {
return new Dimension(100,100);
} else {
return new Dimension(img.getWidth(null)+900, img.getHeight(null)+900);
}
}
public void AnimationPanel() {
javax.swing.Timer timer = new javax.swing.Timer(20, new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
x++;
y++;
repaint();
}
});
timer.start();
}
public static void main(String[] args) {
JFrame f = new JFrame("Load Image Sample");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.add(new ClassC());
f.pack();
f.setVisible(true);
ClassC callanimation = new ClassC(1);
callanimation.AnimationPanel();
}
}
【问题讨论】:
-
首先想到的问题是,为什么是 AWT?
-
相关example :-)
标签: java image swing timer paint