java 如何画图
Java 绘图基础方法
Java 提供了多种绘图方式,主要依赖于 java.awt 和 javax.swing 包中的类。以下是几种常见的绘图方法:
使用 JPanel 和 paintComponent 方法
创建一个继承自 JPanel 的类,重写 paintComponent 方法进行绘图操作。
示例代码:

import javax.swing.*;
import java.awt.*;
class MyPanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(10, 10, 100, 100);
g.drawRect(50, 50, 100, 80);
}
}
public class DrawExample {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(new MyPanel());
frame.setSize(300, 300);
frame.setVisible(true);
}
}
使用 Graphics2D 增强绘图功能
Graphics2D 提供了更丰富的绘图功能,如设置线条粗细、颜色渐变等。
示例代码:
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(new BasicStroke(5));
g2d.setColor(Color.BLUE);
g2d.drawOval(50, 50, 100, 100);
}
使用 JavaFX 绘图
JavaFX 提供了更现代的绘图 API,适合创建复杂的图形界面。
示例代码:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
public class JavaFXDraw extends Application {
@Override
public void start(Stage stage) {
Pane pane = new Pane();
Line line = new Line(10, 10, 100, 100);
pane.getChildren().add(line);
stage.setScene(new Scene(pane, 300, 300));
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
绘制图像文件
可以使用 ImageIO 类加载图片并在面板上绘制。
示例代码:
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
try {
Image image = ImageIO.read(new File("image.png"));
g.drawImage(image, 50, 50, null);
} catch (IOException e) {
e.printStackTrace();
}
}
绘制动态图形
通过定时器 (Timer) 实现动态图形的绘制和更新。
示例代码:
Timer timer = new Timer(100, e -> {
x += 5;
repaint();
});
timer.start();
以上方法涵盖了 Java 绘图的基本和高级操作,适用于不同的应用场景。






