设计一种可绘制各种形状的画笔Painter类,要求用抽象原则,并且具备GUI界面。语言为Java,可绘制的图形为矩形,圆,直线
时间: 2024-09-11 20:13:47 浏览: 63
在Java中,我们可以遵循设计模式中的抽象工厂模式(Abstract Factory Pattern)和装饰者模式(Decorator Pattern),结合Swing或JavaFX等图形用户界面库来创建这个Painter类。这里我会给出一个简化的抽象框架:
```java
import java.awt.*;
import javax.swing.*;
// 抽象画笔接口
public abstract class Painter {
protected Shape shape;
public Painter(Shape shape) {
this.shape = shape;
}
// 绘制抽象方法
public abstract void draw(Graphics g);
// 获取形状
public Shape getShape() {
return shape;
}
}
// 抽象形状接口
public interface Shape {
// 设置形状的属性(如矩形的长宽、圆形的半径)
void setDimensions(double... dimensions);
// 返回形状的基本描述
String getDescription();
}
// 具体形状实现,比如Rectangle和Circle
public class Rectangle extends Shape {
private double width, height;
@Override
public void setDimensions(double w, double h) {
width = w;
height = h;
}
@Override
public String getDescription() {
return "Rectangle [" + width + "x" + height + "]";
}
@Override
public void draw(Graphics g) {
g.fillRect((int)shape.getX(), (int)shape.getY(), (int)width, (int)height);
}
}
public class Circle extends Shape {
private double radius;
@Override
public void setDimensions(double r) {
radius = r;
}
@Override
public String getDescription() {
return "Circle [" + radius + "]";
}
@Override
public void draw(Graphics g) {
g.drawOval((int)shape.getX(), (int)shape.getY(), (int)(radius*2), (int)(radius*2));
}
}
// GUI抽象画布类
public abstract class DrawingCanvas extends JPanel {
protected Painter painter;
public DrawingCanvas(Painter painter) {
this.painter = painter;
}
public abstract void paintComponent(Graphics g);
}
// 具体画布实现,比如DrawingFrame
public class DrawingFrame extends JFrame implements DrawingCanvas {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
painter.draw(g);
}
// 添加事件监听器或菜单选项以便选择形状
public void setPainterShape(Shape newShape) {
painter = new Painter(newShape);
}
}
```
阅读全文