簡體   English   中英

如何根據計時器移動圖像?

[英]How can I move an image based on a timer?

如何根據計時器移動圖像? 我試圖在沒有任何用戶輸入的情況下移動圖像,但是由於我無法移動圖像,我做錯了什么。

我是否錯誤地調用了為實際移動圖像而構建的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();
    }
}

屏幕上的組件不是您要設置動畫的組件...

// 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共享庫的某些部分,但它們並不總是在一起玩的很好;)

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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM