仅绘制一次图像,无需重新绘制

时间:2014-04-16 22:30:34

标签: java swing animation graphics paintcomponent

我在java中编写了简单的动画,并且再次调用paintComponent(Graphics g)方法。

问题是,我在背景中绘制的绘画是随机生成的。因此,每次调用repaint()时,它都会发生变化。

它是通过绘制矩形生成的,所以我需要图形处理程序。

我该如何解决这个问题?

public void paintComponent(Graphics g)
{
   landscape = new Landscape(g); // landscape - attribute

   //...
}

因此很多时候都会调用构造函数:

public class Landscape 
{

    public Landscape(Graphics g)
    {
        Graphics2D g2d = (Graphics2D)g;

        g2d.setColor(new Color(92, 163, 99));

        Random rand = new Random();
        int first = rand.nextInt((800 - 1) + 1) + 1;
        g2d.fillRect(0, 800 - first, 1, first);

        int d = first % 2;
        if(d == 0) d = -1;

        for(int i = 1; i <= 800; i++) {
            int choose = rand.nextInt((1000 - 1) + 1) + 1;

            if(choose > 950) {
                d = -(d);
            }

            if(d == -1) {
                first += 1;                
            } else {
                first -= 1;
            }

            g2d.fillRect(i, 800 - first, 1, first);
        }
    }

} // End Landscape

每次所有点都会改变。

1 个答案:

答案 0 :(得分:4)

将矩形的构造与矩形的图形分开。

在构造函数中构造矩形并在draw方法中绘制矩形。

这是您的Landscape类,重新排列。

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Landscape {

    List<Rectangle> rectangles;

    public Landscape() {
        rectangles = new ArrayList<Rectangle>();

        Random rand = new Random();
        int first = rand.nextInt((800 - 1) + 1) + 1;
        rectangles.add(new Rectangle(0, 800 - first, 1, first));

        int d = first % 2;
        if (d == 0)
            d = -1;

        for (int i = 1; i <= 800; i++) {
            int choose = rand.nextInt((1000 - 1) + 1) + 1;

            if (choose > 950) {
                d = -(d);
            }

            if (d == -1) {
                first += 1;
            } else {
                first -= 1;
            }

            rectangles.add(new Rectangle(i, 800 - first, 1, first));
        }
    }

    public void draw(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(new Color(92, 163, 99));
        for (Rectangle r : rectangles) {
            g2d.fillRect(r.x, r.y, r.width, r.height);
        }
    }

} // End Landscape