一、小组成员及任务分配
成员 | 身份 | 任务 |
吴钧杰 | 组长 | 文件存储、圆的运动类 |
雷宇轩 | 组员 | GUI界面及功能、圆的操作类 |
二、前期调查
通过前期调查,调查中发现”生成小球并进行运动“有以下功能
通过鼠标点击生成随机小球
小球会按照某种轨迹运动
三、功能设计及功能架构图
通过调查总结和团队思考,我们将为程序设计以下功能
通过在空白处单击鼠标生成大小和颜色随机的小球
通过鼠标单击小球来暂停小球,双击小球来删除小球
小球会按照某种轨迹运动
可以通过”pause“和”continue“按钮控制小球运动的暂停和继续
在退出程序时会保存退出时的状态,在下次打开时恢复到上次退出时的状态
功能架构图如下
功能流程图如下
四、UML图
五、项目运行
1.单击鼠标在空白处生成圆
2.单击圆暂停圆的运动
3.双击圆来删除圆
4.双击空白处生成并删除圆
5.通过”pause“和”continue“按钮操控圆运动的暂停和继续
六、关键模块及代码描述
1.圆的生成与删除
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 1) {
// 判断点击的位置是否有圆,有圆则不生成新圆
for (Circle circle : circles) {
if (circle.contains(e.getX(), e.getY())) {
return;
}
}
// 否则生成新圆
int x = e.getX();
int y = e.getY();
int radius = random.nextInt(50) + 10; // random radius between 10 and 60
Color color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)); // random color
Circle circle = new Circle(x, y, radius, color);
circles.add(circle);
} else if (e.getClickCount() == 2) {
// 双击删掉圆
int x = e.getX();
int y = e.getY();
for (Circle circle : circles) {
if (circle.contains(x, y)) {
circles.remove(circle);
break;
}
}
}
}
});
2.生成的圆进行运动
public Circle(int x, int y, int radius, Color color) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
angle = random.nextDouble() * 2 * Math.PI; // 随机生成一个角度
speed = random.nextDouble() * 2 - 1; // 随机生成-1到1之间的速度
}
// 圆的位置的更新的参数
public void updatePosition() {
if (!paused) {
x += Math.cos(angle) * speed;
y += Math.sin(angle) * speed;
angle += 0.1; // 运动
}
}
public void draw(Graphics g) {
g.setColor(color);
g.fillOval(x - radius, y - radius, 2 * radius, 2 * radius);
}
public boolean contains(int x, int y) {
return new Ellipse2D.Double(this.x - radius, this.y - radius, 2 * radius, 2 * radius).contains(x, y);
}
3.将圆的信息存储到文件并在下次打开时加载出来
List<Circle> circles = new ArrayList<>();
try {
Path path = Paths.get("circles.bin");
try (ObjectInputStream in = new ObjectInputStream(Files.newInputStream(path))) {
circles = (List<Circle>) in.readObject();
} catch (IOException | ClassNotFoundException ex) {
ex.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
JFrame frame = new JFrame("Random Circles");
frame.setSize(WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new RandomCircles());
frame.setVisible(true);
RandomCircles.circles = circles;
List<Circle> finalCircles = RandomCircles.circles;
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
try (ObjectOutputStream out = new ObjectOutputStream(Files.newOutputStream(Paths.get("circles.bin")))) {
out.writeObject(finalCircles);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
七、项目总结
这次设计的项目功能较简单,我们小组两个人完成仍有遇到些许难题,说明java编程能力依旧是有待提高;小组合作能力还需加强,配合能力需要不断通过实践去提升。但好在制作出来的程序满足了绝大部分的要求,并加入了小部分的较简单的额外内容。
不足之处及期望
1.圆的运动没有设计得特别有随机性,也没有做出碰撞的效果
2.鼠标点击有些许卡顿,在延时上需要有改进
3.界面偏简单,需要学习更有关界面设计的编程技术
4.没有考虑到重置界面的功能,导致生成大量圆时,需要通过多次点击来删除