repaint()绘制比paintComponent()慢?

时间:2015-03-03 05:53:39

标签: java swing awt actionlistener paintcomponent

我正在绘制使用paintComponent()定义的车辆对象。 因为车辆可以移动,我实现ActionListener并设置Timer()来触发。

结果,我的车辆可以移动。但它有点“颤抖”。当我继续调整窗口大小以调用paintComponent()时,移动变得平滑。当我没有调整窗口大小(不调用paintComponent)时,它会再次跳过。为什么?如何解决?

public class VehiclesComponent extends JComponent implements ActionListener{
    private Vehicle[] vehicles;
    private Timer timer;

    public VehiclesComponent(int n){
        vehicles = Vehicle.generateVehicle(n);
        timer = new Timer(5,this);
    } 

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;

        for (int i=0; i<vehicles.length; i++) {
            vehicles[i].draw(g2);
        }

        // may change later
        timer.start();
    }

    @Override
    public void actionPerformed(ActionEvent e){

        //check collision in here
        for (Vehicle v : vehicles) {
            if (Vehicle.intersectsOther(v, vehicles)) {
                v.collisionSideEffect();
            }
        }

        //move all in here

        for (Vehicle v : vehicles ) {
            v.move();
        }

        repaint(); 
        //?? repaint slower than paintComponent
    }


} 

1 个答案:

答案 0 :(得分:1)

首先看一下Painting in AWT and Swing。请注意,repaint仅是对RepaintManager的建议,RepaintManager可能会选择将多个repaint调用合并为较少数量的实际绘画事件。

确保你正在调用super.paintComponent,否则你最终会得到一些奇怪的绘画文物。

不要直接或间接地从任何绘制方法中修改组件或ant其他组件的状态,这将导致发出新的repaint请求,这可能导致绘制循环可能消耗CPU周期的事件。这意味着,请勿拨打timer.start()

如果没有一个可运行的例子,我一起蹒跚而行。现在这是动画10,000个Vehicle个(长方形)的动画,所以它大大超过杀戮,但它应该提供点...

Noise

(gif仅以7fps运行,而不是200fps)

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new VehiclesComponent(10000));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class VehiclesComponent extends JComponent implements ActionListener {

        private Vehicle[] vehicles;
        private Timer timer;

        public VehiclesComponent(int n) {
            vehicles = Vehicle.generateVehicle(n, getPreferredSize());
            timer = new Timer(5, this);

            timer.start();
        }

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

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;

            for (int i = 0; i < vehicles.length; i++) {
                vehicles[i].draw(g2);
            }
        }

        @Override
        public void actionPerformed(ActionEvent e) {

            //check collision in here
//          for (Vehicle v : vehicles) {
//              if (Vehicle.intersectsOther(v, vehicles)) {
//                  v.collisionSideEffect();
//              }
//          }

        //move all in here
            for (Vehicle v : vehicles) {
                v.move(this.getSize());
            }

            repaint();
            //?? repaint slower than paintComponent
        }

    }

    public static class Vehicle {

        protected static final int SIZE = 5;
        protected static final Color[] COLORS = new Color[]{
            Color.BLACK,
            Color.BLUE,
            Color.CYAN,
            Color.DARK_GRAY,
            Color.GREEN,
            Color.MAGENTA,
            Color.ORANGE,
            Color.PINK,
            Color.RED,
            Color.WHITE,
            Color.YELLOW
        };

        private int x = 0;
        private int y = 0;

        private int xDelta;
        private int yDelta;

        private Shape car;
        private Color color;

        public static Vehicle[] generateVehicle(int count, Dimension bounds) {

            Vehicle[] vehicles = new Vehicle[count];
            for (int index = 0; index < vehicles.length; index++) {
                vehicles[index] = new Vehicle(bounds);
            }

            return vehicles;

        } 

        public Vehicle(Dimension size) {

            x = (int)(Math.random() * (size.width - SIZE));
            y = (int)(Math.random() * (size.height - SIZE));

            xDelta = (int)(Math.random() * 3) + 1;
            yDelta = (int)(Math.random() * 3) + 1;
            car = new Rectangle(SIZE, SIZE);

            color = COLORS[(int)(Math.random() * COLORS.length)];

        }

        public void move(Dimension size) {
            x += xDelta;
            y += yDelta;

            if (x < 0) {
                x = 0;
                xDelta *= -1;
            } else if (x + SIZE > size.width) {
                x = size.width - SIZE;
                xDelta *= -1;
            }
            if (y < 0) {
                y = 0;
                yDelta *= -1;
            } else if (y + SIZE > size.height) {
                y = size.height - SIZE;
                yDelta *= -1;
            }

        }

        public void draw(Graphics2D g2) {
            g2.translate(x, y);
            g2.setColor(color);
            g2.fill(car);
            g2.translate(-x, -y);
        }

    }

}

您还可以查看this example,它会随机向下渲染4500张图像并展示一些优化技巧。

您还可以查看能够在方向和旋转方面设置动画的this example,超过10,000张图像