在Java中动画化矩形

use*_*860 1 java animation swing 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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Hov*_*els 10

在paint或paintComponent方法中没有程序逻辑,并且通过逻辑,我的意思是具有"运动"的for循环,因为它不起作用.你想要

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

例如

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

}
Run Code Online (Sandbox Code Playgroud)