如何根据计时器移动图像?我试图让图像移动而没有任何用户输入但我做错了,因为我无法移动图像。
我是否错误地调用了我为实际移动图像而构建的方法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();
}
}
答案 0 :(得分:4)
屏幕上的组件不是您要设置动画的组件......
// Create first instance here...
f.add(new ClassC());
f.pack();
f.setVisible(true);
// Create second instance here...
ClassC callanimation = new ClassC(1);
callanimation.AnimationPanel();
相反,这会让你开始
ClassC callanimation = new ClassC();
callanimation.AnimationPanel();
f.add(callanimation);
f.pack();
f.setVisible(true);
ps-我也非常小心,你正在混合框架。虽然AWT和Swing共享库的某些部分,但它们并不总能很好地协同工作;)
答案 1 :(得分:3)
public ClassC(int x)
{
}
为什么这是空的?什么是x?
f.add(new ClassC()); <-- you created a ClassC() here
f.pack();
f.setVisible(true);
ClassC callanimation = new ClassC(1); <-- you created a new ClassC here
这两个是不同的,因为你再次创建它们。
尝试做:
ClassC callanimation = new ClassC(1);
f.add(callanimantion);
f.pack();
f.setVisible(true);
callanimation.AnimationPanel();