我在将形状(圆形和矩形)绘制到框架中时遇到了困难。
我已经创建了实现 Shape 接口的 Circle 和 Rectangle 类。然后,我创建了 DrawableCircle 和 DrawableRectangle 类,它们适当地扩展了 Circle 和 Rectangle 类,并实现了 Drawable 接口。
我现在正在尝试创建一个 ShapesDriver 类,它扩展了 Frame 并在其中包含 main 方法和 paint(Graphics g) 方法。在 ShapesDriver 中,我需要创建一个 Drawable 类型的 ArrayList。此 ArrayList 包含 DrawableCircle 和 DrawableRectangle 的实例。在paint 方法中,我必须遍历ArrayList 并为每个形状调用draw 方法。
这就是我被困的地方......
任何帮助,将不胜感激!
形状界面
public interface Shape {
public double area();
}
圆班
public class Circle implements Shape{
private int radius;
private double area;
public Circle(int r){
radius = r;
}
@Override
public double area() {
area = Math.PI * (radius * radius);
return area;
}
}
矩形类
public class Rectangle implements Shape{
double height;
double width;
double area;
public Rectangle(double h, double w){
height = h;
width = w;
}
@Override
public double area() {
area = height * width;
return area;
}
}
可绘制界面
import java.awt.Color;
import java.awt.Graphics;
public interface DrawableInterface {
public void setColor(Color c);
public void setPosition(int x, int y);
public void draw(Graphics g);
}
可绘制圆
import java.awt.Color;
import java.awt.Graphics;
public class DrawableCircle extends Circle implements DrawableInterface{
private Color col;
private int posX;
private int posY;
public DrawableCircle(int r){
super(r);
}
@Override
public void setColor(Color c) {
col = c;
}
@Override
public void setPosition(int x, int y) {
posX = x;
posY = y;
}
@Override
public void draw(Graphics g) {
g.setColor(col);
g.drawOval(posX, posY, 15, 15);
}
}
可绘制矩形
import java.awt.Color;
import java.awt.Graphics;
public class DrawableRectangle extends Rectangle implements DrawableInterface{
private Color col;
private int posX;
private int posY;
public DrawableRectangle(double h, double w){
super(h, w);
}
@Override
public void setColor(Color c) {
col = c;
}
@Override
public void setPosition(int x, int y) {
posX = x;
posY = y;
}
@Override
public void draw(Graphics g) {
g.setColor(col);
g.drawRect(posX,posY,10,10);
}
}
形状驱动程序
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
public class ShapesDriver extends Frame {
static ArrayList<DrawableInterface> shapesArr = new ArrayList<DrawableInterface>();
public ShapesDriver() {
super("Shapes Object Array");
setSize(400, 300);
setLocation(200, 200);
setVisible(true);
}
public static void main(String[] args) {
DrawableCircle c = new DrawableCircle(500);
c.setColor(Color.GREEN);
c.setPosition(25, 25);
DrawableRectangle r = new DrawableRectangle(100, 50);
r.setColor(Color.RED);
r.setPosition(75, 75);
shapesArr.add(c);
shapesArr.add(r);
ShapesDriver shapeFrame = new ShapesDriver();
shapeFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
@Override
public void paint(Graphics g) {
for (DrawableInterface s : shapesArr) {
super.paint(g);
s.draw(g);
}
}
}