如何让计时器更改图片

如何让计时器更改图片

本文介绍了如何让计时器更改图片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在完成 Swing 计时器后更改图像?我知道它在完成后会播放 actionPerformed 类中的代码,但我无法让它工作.

How do I get an image to change after a Swing timer is done? I know it plays the code in the actionPerformed class when it's done, but I could not get it to work.

如果有任何改变,我会使用paint方法绘制图像:)

I have the image painted using the paint method if that changes anything :)

public class Sprite extends JFrame implements ActionListener{

private Board board;
private Timer timer;


public Sprite() {

    timer = new Timer(1000, this);
    grow=false;


}
public Image grow() {
    if(grow)
         return image;
    else
         return other_image;
}
public void actionPerformed(ActionEvent e) {
    grow = false;
    board.repaint();
}

EDIT 代码是这样的 ^^

推荐答案

我无法发表评论,所以我只会在这里说,并在您回答时进行编辑,到目前为止您的代码是什么样的?你试过什么?有很多方法可以实现您想要的,但您的问题有点缺乏细节.

I can't comment so I will just say it here and edit when you answer, What is your code like so far? what have you tried ? there are quite a few ways to achieve what you want, but your question is sort of lacking detail.

您没有显示名为增长的字段,并且拥有一个名为增长的字段/变量并拥有一个名为增长的方法并不是一个好主意.

edit:You arn't showing a field named grow, and it isn't a good idea to have a field/variable by the name of grow and have a method named grow.

你可以根据自己的情况做一件事.

One thing you can do according to yours would be something like.

public class Sprite extends JFrame implements ActionListener {

    public boolean Grown;
    public Board board; // never set in your example,
                        // nor do i have any idea what it is for
    public Timer timer;
    public BufferedImage UngrownImage; // Initialize these images yourself
    public BufferedImage GrownImage;

    public sprite() {

        Grown = false;
        timer = new Timer(1000, this);
        timer.start();
    }

    public void actionPerformed(ActionEvent e) {

        Grown = true;
        board.repaint(); // you may want to call super.repaint() too
                         // but again I do not know what board is.
    }

    // unless your "Board" is taking care of it, here you can paint the images
    public void paint(Graphics g) {

        super.paint(g);

        int imgX = 0, imgY = 0;

        if(Grown && GrownImage != null)
            g.drawImage(GrownImage, imgX, imgY, null);
        else if(UngrownImage != null)
            g.drawImage(UngrownImage, imgX, imgY, null);
        else
            System.out.println("error: No images loaded");

    }
}

如果您有任何不明白的地方,请告诉我,我很乐意向您总结,我认为所有这些都是您已经使用过的东西,判断您正在尝试做什么.

If there is anything you do not understand let me know, I will gladly summarize it to you, I assumed that all this is stuff you have worked with, judging off of what you are trying to do.

这篇关于如何让计时器更改图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 07:44