【问题标题】:How can I move an image based on a timer?如何根据计时器移动图像?
【发布时间】: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


【解决方案1】:
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();

【讨论】:

    【解决方案2】:

    屏幕上的组件不是您正在制作动画的组件...

    // 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 共享库的某些部分,但它们并不总是一起玩得很好;)

    【讨论】:

    • 很抱歉浪费了您的时间。我今天的思维一定不正确。非常感谢。
    • 欢迎来到我的世界:P
    • @moonbeamer2234 : 不要在JFrame 中添加WindowListener,如果你只写f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE),那将完成几乎相同的任务:-)
    • @nIcEcOw java.awt.Frame 没有 setDefaultCloseOperation。这将假设 OP 正在使用 Swing ;)
    • @MadProgrammer :但在主要方法中我正在观看 JFrame 被使用...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多