在Java中动画化矩形

时间:2012-04-03 02:19:01

标签: java swing animation draw

我一直试图让这个矩形移动我使用for循环创建的。这段代码发生的一切就是有一个原始的矩形,然后在那个矩形旁边有一个新的矩形。没有动画发生,只有那两个矩形显示在窗口上。有什么方法可以让这个矩形动画化?

import java.awt.*;
import javax.swing.*;

public class Gunman extends JComponent {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    public int x = 10;
    public int y = 10;
    public int width = 8;
    public int height = 10;
    public void paint(Graphics g) {
        g.setColor(Color.red);
        g.drawRect (x, y, width, height);  
        g.fillRect (x, y, width, height);
        for(int i = 0; i<=1024; i++){
            g.setColor(Color.red);
            g.drawRect(x++, y, width, height);
            g.fillRect(x++, y, width, height);
        }
    }
}

3 个答案:

答案 0 :(得分:10)

在paint或paintComponent方法中没有程序逻辑,而且逻辑上,我的意思是带有“运动”的for循环,因为它不起作用。你想要

  • 几乎从不在JComponent的paint方法中绘制,而是在其paintComponent方法中绘制。
  • 不要忘记调用super.paintComponent(g)方法,通常是paintComponent(g)覆盖中的第一个方法调用。
  • 使用Swing Timer逐步更改x和y值
  • 在进行更改后在JComponent上调用repaint()

例如

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Gunman extends JComponent {

   private static final long serialVersionUID = 1L;
   private static final int PREF_W = 900;
   private static final int PREF_H = 700;
   private static final int TIMER_DELAY = 30;
   public int rectX = 10;
   public int rectY = 10;
   public int width = 8;
   public int height = 10;

   public Gunman() {
      new Timer(TIMER_DELAY, new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent actEvt) {
            if (rectX < PREF_W && rectY < PREF_H) {
               rectX++;
               rectY++;
               repaint();
            } else {
               ((Timer)actEvt.getSource()).stop();
            }
         }
      }).start();
   }


   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

   public void paintComponent(Graphics g) {
      super.paintComponent(g);
      g.setColor(Color.red);
      g.drawRect(rectX, rectY, width, height);
      g.fillRect(rectX, rectY, width, height);
   }

   public int getRectX() {
      return rectX;
   }

   public void setRectX(int rectX) {
      this.rectX = rectX;
   }

   public int getRectY() {
      return rectY;
   }

   public void setRectY(int rectY) {
      this.rectY = rectY;
   }

   private static void createAndShowGui() {
      Gunman mainPanel = new Gunman();

      JFrame frame = new JFrame("Gunman");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }

}

答案 1 :(得分:0)

有很多种动画方式。这是另一个例子。注意后台线程中repaint()的位置。这直接在JFrame上绘制。在JPanels上绘画时使用paintComponent()。

public static void main(String args[]) throws Exception {
new JFrame("Draw a red box") {
  Point pointStart = new Point(50,50);
  Point pointEnd   = new Point(200,200);
  public void paint(Graphics g) {
    super.paint(g);
    if (pointStart != null) {
      g.setColor(Color.RED);
      g.drawRect(pointStart.x, pointStart.y, pointEnd.x, pointEnd.y);
    }}{
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    setSize(300, 300);
    setLocation(300, 300);
    setVisible(true);
    Thread t = new Thread(new Runnable() {
      public void run() {
        while (pointEnd.x > 0 && pointEnd.y > 0) {
          pointEnd = new Point(--pointEnd.x, --pointEnd.y);
          repaint();
          try {
            Thread.sleep(22);
          } catch (InterruptedException e) {
            e.printStackTrace();
        }}
        pointStart = null;
        pointEnd = null;
    }});
    t.setDaemon(true);
    t.start();
  }};}

答案 2 :(得分:-1)

更新:好的以前的答案从旧内存不太好,这是获得动画quicksmart的最快,最便宜,最脏的方法,你可以按原样复制和编译代码:

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;

public class Test extends JFrame {

    public Gunman g = new Gunman();

    public static void main( String[] args ) {
        Test t = new Test();
        t.setSize( 800, 600 );
        t.setVisible( true );
        t.getContentPane().add( t.g );

        while ( true ) {
            t.g.x = t.g.x + 1;
            t.g.y = t.g.y + 1;
            t.repaint();
            try {
                Thread.sleep( 100 );
            } catch ( InterruptedException e ) {
            }
        }
    }

    public void paintComponent( Graphics g ) {
        g.clearRect( 0, 0, 800, 600 );
    }
}


class Gunman extends JComponent {

    private static final long serialVersionUID = 1L;
    public int x = 10;
    public int y = 10;
    public int width = 8;
    public int height = 10;

    public void paintComponent( Graphics g ) {
        g.setColor( Color.red );
        g.fillRect( x, y, width, height );
    }
}

这里有很多快捷方式,正如鳗鱼的气垫船所说,这不是一种“理想”的方式,但它具有基本结构。你有一个画布(我已经使用过JFrame,同样不是真的推荐),你添加了一个组件。你必须覆盖paintComponent(如果你使用swing,我建议你这样做),这将绘制你的组件 然后,您需要以某种方式更改组件的位置(建议对执行此操作的对象进行适当的方法调用),并要求画布重新绘制自己。
我已经包含了等待你可以看到发生了什么,但如果你正在考虑游戏编程,你应该考虑创建一个游戏循环来管理这个,我推荐在Java中使用Killer游戏编程,你可以获得一个免费的电子书版本快速谷歌搜索。