java如何画线
使用 Graphics 类绘制线条
在 Java 中,可以通过 Graphics 或 Graphics2D 类绘制线条。以下是一个简单的示例,展示如何在 JPanel 上绘制一条直线:
import javax.swing.*;
import java.awt.*;
public class DrawLineExample extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(50, 50, 200, 200); // 从 (50,50) 到 (200,200) 画线
}
public static void main(String[] args) {
JFrame frame = new JFrame("Draw Line Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.add(new DrawLineExample());
frame.setVisible(true);
}
}
使用 Graphics2D 绘制更复杂的线条
Graphics2D 提供了更多自定义选项,如线条宽度、颜色和抗锯齿效果:
import javax.swing.*;
import java.awt.*;
public class DrawLineWithGraphics2D extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.setStroke(new BasicStroke(3)); // 设置线条宽度为 3 像素
g2d.drawLine(50, 50, 200, 200);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Graphics2D Line Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.add(new DrawLineWithGraphics2D());
frame.setVisible(true);
}
}
绘制多条线段
可以使用 drawLine 多次调用绘制多条线段,或使用 Polygon 类绘制折线:
import javax.swing.*;
import java.awt.*;
public class DrawMultipleLines extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLUE);
g2d.drawLine(50, 50, 100, 50);
g2d.drawLine(100, 50, 100, 100);
g2d.drawLine(100, 100, 50, 100);
g2d.drawLine(50, 100, 50, 50);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Multiple Lines Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.add(new DrawMultipleLines());
frame.setVisible(true);
}
}
使用 Path2D 绘制自定义路径
Path2D 类允许定义更复杂的路径,包括直线和曲线:
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Path2D;
public class DrawPathExample extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
Path2D path = new Path2D.Double();
path.moveTo(50, 50); // 起点
path.lineTo(200, 50); // 水平线
path.lineTo(200, 200); // 垂直线
path.closePath(); // 闭合路径
g2d.draw(path);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Path2D Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.add(new DrawPathExample());
frame.setVisible(true);
}
}
以上方法适用于 Swing 和 AWT 绘图。如果需要更高级的图形处理,可以考虑使用 JavaFX 的 Canvas 或 Shape API。







