簡體   English   中英

timer.schedule()根本不起作用(在Java中)

[英]timer.schedule() in not working at all (in Java)

我用Java開發了一個簡單的程序,可以在畫布上繪制一個矩形。 然后矩形開始沿X軸從左到右移動。 但是timer.schedule()函數不起作用。 以下是代碼:-

package firstanimation;

import java.awt.*;
import java.util.Timer;


public class FirstAnimation {

    public static void main(String[] args) {

        Frame frame = new Frame("SomeRandomName");

        frame.setBounds(50, 50, 700, 500);
        frame.setBackground(Color.red);

        MyCanvas canvas = new MyCanvas();

        frame.add(canvas);
        frame.setVisible(true);

        Graphics graph = frame.getGraphics();

        Timer timer = new Timer();
        Task task = new Task(canvas, graph);

        timer.schedule(task, 1000,1000);

    }
}



package firstanimation;
import java.awt.*;

public class MyCanvas extends Canvas{

    public int x,y,width,height;

    public MyCanvas()
    {
        x = 0;
        y = 0;
        width = 50;
        height = 50;
    }

    @Override
    public void paint(Graphics g) {
        g.setColor(Color.LIGHT_GRAY);
        g.fillRect(x, y, width, height);
    }

    @Override
    public void update(Graphics g) {
        x+=10;
        g.fillRect(x, y, width, height);
    }



}



package firstanimation;
import java.util.TimerTask;
import java.awt.Graphics;

public class Task extends TimerTask{

    private MyCanvas canvas;
    private Graphics graphics;

    public Task(MyCanvas can, Graphics g)
    {
        super();
        canvas = can;
        graphics = g;
        canvas.paint(g);
    }

    @Override
    public void run() {
        canvas.update(graphics);
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

}

但是奇怪的是...每次我最大化並恢復框架時,盒子都在移動。 為什么會這樣呢?

“但是奇怪的是……每次我最大化並恢復框架時,盒子都在移動。為什么會這樣?”

因為repaint()當調整被稱為其更新的圖形, 應該做的,而不是試圖調用, paint

但...

還有很多事情錯了。

既然這是您的第一個動畫(包firstanimation;),那么讓我開始正確的方向。

  1. 不要使用畫布。 請改用JPanelJComponent 在執行此操作時,不要覆蓋paint ,而要覆蓋paintComponent 另外,請確保調用super.paintComponent以免在動畫過程中出現任何繪畫偽像。

     public class MyCanvas extends JPanel { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); //painting code } } 
  2. 切勿在組件上使用getGraphics進行繪畫。

  3. 您永遠不必顯式地調用paint paint[Component]方法將為您隱式調用。 repaint()簡單調用將重新繪制組件。

  4. 我剛剛意識到您正在使用所有AWT組件。 不要使用它們,它們已經過時了。 而是使用Swing組件。 它們中的大多數只是以J JFrame ,例如Frame > JFrame 它們在javax.swing.*包中。

  5. 對於動畫,請使用javax.swing.Timer 您可以在如何使用計時器中看到更多信息。 基本構造是

     Timer ( int delayInMillis, ActionListener listener ) 

    其中delayInMillis是刻度之間(在本例中為動畫)之間延遲的時間,而ActionListener偵聽“刻度”。 每次打勾時,都會調用ActionListeneractionPerformed 在這里,您可以放置​​代碼來更新用於動畫的任何變量。


我建議您閱讀教程“ 執行自定義繪畫”以了解正確的繪畫方法。

這是一個簡單的示例,上面提到了所有要點

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class AnimateBall extends JPanel {

    private static final int D_W = 500;
    private static final int D_H = 300;

    private Ball ball;

    public AnimateBall() {
        Random rand = new Random();
        int randX = rand.nextInt(D_W);
        int randY = rand.nextInt(D_H);
        ball = new Ball(randX, randY);

        Timer timer = new Timer(15, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ball.animate();

                repaint();
            }
        });
        timer.start();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
            ball.drawBall(g);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(D_W, D_H);
    }

    public class Ball {

        int x = 0;
        int y = 0; // Current ball position
        int dx = 4; // Increment on ball's x-coordinate
        int dy = 4; // Increment on ball's y-coordinate
        int radius = 15; // Ball radius

        public Ball(int x, int y) {
            this.x = x;
            this.y = y;
        }

        Color color = new Color((int) (Math.random() * 256),
                (int) (Math.random() * 256), (int) (Math.random() * 256));

        public void drawBall(Graphics g) {
            g.setColor(color);
            g.fillOval(x - radius, y - radius, radius * 2, radius * 2);
        }

        public void animate() {
            if (x < 0 || x > getWidth()) {
                dx = -dx;
            }
            if (y < 0 || y > getHeight()) {
                dy = -dy;
            }
            // Adjust ball position
            x += dx;
            y += dy;
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new AnimateBall());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}

暫無
暫無

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

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