Files
2025ClassOfJava/C06 Polymorphism/src/test/ShapeDrawerTest.java
2025-10-29 00:52:52 +08:00

78 lines
2.9 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package test;
import shape.Circle;
import shape.Rectangle;
import javax.swing.*;
import java.awt.*;
public class ShapeDrawerTest extends JFrame {
/*******请在下面添加**************/
// 【任务1】定义一个包含5个元素的圆形数组
Circle[] circles = new Circle[5];
Rectangle[] rectangles = new Rectangle[2];
private shape.Shape[] shapes = new shape.Shape[4];
/*******请在上面添加**************/
// 初始化图形
private void initShapes() {
/*******请在下面添加**************/
// 【任务2】采用无参构造添加一个红色坐标为(100,100)半径为50的圆形并加入对应数组
shapes[0] = new Circle();
((Circle)shapes[0]).setX(100);
((Circle)shapes[0]).setY(100);
((Circle)shapes[0]).setRadius(50);
((Circle)shapes[0]).setColor(Color.RED);
// 【任务3】采用有参构造添加一个黄色坐标为(150,300)半径为70的圆形并加入对应数组
shapes[1] = new Circle(Color.YELLOW, 150, 300, 70);
// 【任务4】采用无参构造添加一个绿色坐标为(250,80)宽为100高为80的矩形并加入对应数组
shapes[2] = new Rectangle();
((Rectangle)shapes[2]).setX(250);
((Rectangle)shapes[2]).setY(80);
((Rectangle)shapes[2]).setWidth(100);
((Rectangle)shapes[2]).setHeight(80);
((Rectangle)shapes[2]).setColor(Color.GREEN);
// 【任务5】采用有参构造添加一个粉色坐标为(300,300)宽为120高为60的矩形
shapes[3] = new Rectangle(Color.PINK, 300, 300, 120, 60);
// 【任务6】下移动第二个矩形50个单位
((Rectangle)shapes[3]).setY(this.getY()-50);
/*******请在上面添加**************/
}
// 重写绘制方法
@Override
public void paint(Graphics g) {
super.paint(g);
/*******请在下面添加**************/
// 绘制所有图形
// 【任务4】采用增强型for循环绘制所有图形
for (shape.Shape shape : shapes) {
shape.draw(g);
if (shape instanceof Circle) {
((Circle)shape).drawCenterMark(g);
}
if (shape instanceof Rectangle) {
((Rectangle)shape).drawDiagonals(g);
}
}
/*******请在上面添加**************/
// 绘制标题
g.setColor(Color.BLACK);
g.drawString("Java继承图形绘制示例", 300, 50);
}
public ShapeDrawerTest() {
// 初始化窗口
setTitle("图形绘制程序");
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// 创建各种图形对象
initShapes();
}
public static void main(String[] args) {
new ShapeDrawerTest().setVisible(true);
}
}