用java生成画图工具的代码
时间: 2024-05-27 21:12:15 浏览: 49
以下是使用Java生成画图工具的示例代码:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class DrawingTool extends JFrame {
private static final long serialVersionUID = 1L;
private ArrayList<Point> points = new ArrayList<Point>();
public DrawingTool() {
setTitle("Drawing Tool");
setSize(500, 500);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
points.add(e.getPoint());
repaint();
}
});
getContentPane().add(panel);
setVisible(true);
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.BLACK);
for (int i = 0; i < points.size() - 1; i++) {
Point p1 = points.get(i);
Point p2 = points.get(i + 1);
g.drawLine(p1.x, p1.y, p2.x, p2.y);
}
}
public static void main(String[] args) {
new DrawingTool();
}
}
阅读全文