如何用java画画
使用Java绘图基础
Java提供了多种绘图方式,主要通过java.awt和javax.swing包实现。最常用的类是Graphics和Graphics2D,它们提供了绘制图形、文本和图像的方法。
创建自定义绘图区域需要继承JPanel并重写paintComponent方法:
import javax.swing.*;
import java.awt.*;
class DrawingPanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// 绘图代码写在这里
}
}
基本图形绘制
Graphics类提供了一系列绘制基本图形的方法:
// 画直线
g.drawLine(x1, y1, x2, y2);
// 画矩形
g.drawRect(x, y, width, height);
g.fillRect(x, y, width, height);
// 画椭圆/圆
g.drawOval(x, y, width, height);
g.fillOval(x, y, width, height);
// 画多边形
int[] xPoints = {x1, x2, x3};
int[] yPoints = {y1, y2, y3};
g.drawPolygon(xPoints, yPoints, nPoints);
使用Graphics2D增强功能
Graphics2D是Graphics的子类,提供了更高级的绘图功能:
Graphics2D g2d = (Graphics2D)g;
// 设置线条粗细
g2d.setStroke(new BasicStroke(3.0f));
// 设置颜色
g2d.setColor(Color.RED);
// 绘制带旋转的图形
AffineTransform oldTransform = g2d.getTransform();
g2d.rotate(Math.toRadians(45));
g2d.drawRect(50, 50, 100, 50);
g2d.setTransform(oldTransform);
创建绘图窗口
将绘图面板添加到JFrame中显示:
public static void main(String[] args) {
JFrame frame = new JFrame("绘图示例");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.add(new DrawingPanel());
frame.setVisible(true);
}
处理用户交互
实现鼠标事件监听来创建交互式绘图:
class DrawingPanel extends JPanel {
private List<Point> points = new ArrayList<>();
public DrawingPanel() {
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
points.add(e.getPoint());
repaint();
}
});
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for(Point p : points) {
g.fillOval(p.x, p.y, 5, 5);
}
}
}
双缓冲技术
避免闪烁可以使用双缓冲:
class DoubleBufferedPanel extends JPanel {
public DoubleBufferedPanel() {
setDoubleBuffered(true);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// 绘图代码
}
}
保存绘图结果
将绘图保存为图像文件:

BufferedImage image = new BufferedImage(panel.getWidth(), panel.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
panel.paint(g2d);
try {
ImageIO.write(image, "PNG", new File("drawing.png"));
} catch (IOException e) {
e.printStackTrace();
}






