在Java中绘制一个对象属性的图像

时间:2011-12-11 23:20:31

标签: java image swing graphics

以下是设置:

我有一个名为Sprite的类,它包含一个名为Animal的子类的图像,它是World类中动物数组的一部分。使用完成所有图形的Canvas类,我如何才能获得图像?

Survival.class - 主类

package survival;
import javax.swing.*;

public class Survival {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Survival");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(1000, 750);

        Canvas g = new Canvas();
        frame.add(g);

        frame.setVisible(true);

        World environment = new World(10, 25, 1000, 750);
        environment.step();
    }
}

Canvas.class - 处理所有绘图

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

public class Canvas extends JPanel {
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2D = (Graphics2D) g;
    }
}

World.class - 创造动物

package survival;

public class World {
    private int width = 1000;
    private int height = 750;

    private Animal[] animals;
    private Plant[] plants;

    public World(int animalNumber, int plantNumber, int width, int height) {
        this.width = width;
        this.height = height;

        animals = new Animal[animalNumber];
        for (int i = 0; i < animalNumber; i++) {
            animals[i] = new Animal(0,0);
        }

        plants = new Plant[plantNumber];
        for (int i = 0; i < plantNumber; i++) {
            plants[i] = new Plant(0,0);
        }
    }

    public void step() {
        for (int i = 0; i < plants.length; i++) {
            plants[i].move();
        }
        for (int i = 0; i < animals.length; i++) {
            animals[i].move();
        }
    }    

    public int getWidth() {
        return width;
    }
    public int getHeight() {
        return height;
    }
}

Sprite.class - 动物的超类,包含图像!

package survival;

public class Sprite {
    private Image; //IMAGE I NEED!!!
    private double x;
    private double y;

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

    public void move() {
        x += 1;
        y += 1;
    }

    public void setX(int x) {
        this.x = x;
    }
    public void setY(int y) {
        this.y = y;
    }
}

Animal.class - 动物的子类

package survival;

public class Animal extends Sprite {
    public Animal(int x, int y) {
        super(x, y);
    }
}