java实现:加入按钮,可实现添加圆形,线条,实现一个简单的绘图板程序
时间: 2024-02-03 16:03:34 浏览: 84
基于Java设计的绘图工具【100011660】
5星 · 资源好评率100%
好的,以下是一个简单的Java绘图板程序的实现,具体实现思路和代码注释在代码中已经给出。
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
public class SimplePaint extends JFrame {
// 定义绘图区
private DrawingBoard drawingBoard;
public SimplePaint() {
super("SimplePaint");
// 初始化绘图区
drawingBoard = new DrawingBoard();
getContentPane().add(drawingBoard, BorderLayout.CENTER);
// 初始化工具栏
JToolBar toolBar = new JToolBar();
getContentPane().add(toolBar, BorderLayout.NORTH);
// 添加圆形按钮
JButton circleButton = new JButton("Circle");
circleButton.addActionListener(e -> {
// 在绘图区添加圆形
drawingBoard.addShape(new Circle(drawingBoard.getMousePosition()));
});
toolBar.add(circleButton);
// 添加线条按钮
JButton lineButton = new JButton("Line");
lineButton.addActionListener(e -> {
// 在绘图区添加线条
drawingBoard.addShape(new Line(drawingBoard.getMousePosition()));
});
toolBar.add(lineButton);
// 设置窗口大小和可见性
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args) {
new SimplePaint();
}
// 自定义绘图区
private static class DrawingBoard extends JPanel {
// 保存绘制的图形
private ArrayList<Shape> shapes = new ArrayList<>();
public DrawingBoard() {
// 添加鼠标监听器,实现绘图功能
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
// 获取当前按钮状态
int button = e.getButton();
if (button == MouseEvent.BUTTON1) {
// 添加图形
addShape(new Circle(e.getPoint()));
}
}
});
}
// 添加图形
public void addShape(Shape shape) {
shapes.add(shape);
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// 绘制所有图形
for (Shape shape : shapes) {
shape.draw(g);
}
}
}
// 自定义图形接口
private interface Shape {
// 绘制图形
void draw(Graphics g);
}
// 自定义圆形类
private static class Circle implements Shape {
// 圆心坐标
private Point center;
public Circle(Point center) {
this.center = center;
}
@Override
public void draw(Graphics g) {
// 计算圆的左上角坐标和半径
int x = center.x - 25;
int y = center.y - 25;
int r = 50;
// 绘制圆形
g.drawOval(x, y, r, r);
}
}
// 自定义线条类
private static class Line implements Shape {
// 起点坐标
private Point start;
public Line(Point start) {
this.start = start;
}
@Override
public void draw(Graphics g) {
// 获取当前鼠标位置
Point end = MouseInfo.getPointerInfo().getLocation();
// 绘制线条
g.drawLine(start.x, start.y, end.x, end.y);
}
}
}
```
阅读全文