java如何填实线
绘制实线的方法
在Java中,可以通过Graphics或Graphics2D类绘制实线。使用drawLine方法或Graphics2D的setStroke方法结合draw方法实现。
使用Graphics.drawLine绘制实线
import java.awt.*;
import javax.swing.*;
public class DrawLineExample extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(50, 50, 200, 50); // 绘制从(50,50)到(200,50)的实线
}
public static void main(String[] args) {
JFrame frame = new JFrame("实线示例");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawLineExample());
frame.setSize(300, 150);
frame.setVisible(true);
}
}
使用Graphics2D绘制自定义宽度实线
import java.awt.*;
import javax.swing.*;
public class DrawThickLineExample extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(new BasicStroke(3)); // 设置线宽为3像素
g2d.drawLine(50, 50, 200, 50); // 绘制粗实线
}
public static void main(String[] args) {
JFrame frame = new JFrame("粗实线示例");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawThickLineExample());
frame.setSize(300, 150);
frame.setVisible(true);
}
}
绘制多段实线或形状边框
通过drawPolyline或drawPolygon方法可以绘制多段实线:
int[] xPoints = {50, 100, 150, 200};
int[] yPoints = {50, 100, 50, 100};
g.drawPolyline(xPoints, yPoints, 4); // 绘制连接4个点的折线
使用Shape对象绘制实线边框
通过Graphics2D绘制Shape对象的实线边框:

Rectangle rect = new Rectangle(50, 50, 100, 60);
g2d.draw(rect); // 绘制矩形的实线边框
注意事项
- 默认情况下
drawLine绘制的实线宽度为1像素。 - 需要更复杂的线型(如虚线)时,可使用
BasicStroke的构造参数指定。 - 绘图代码通常放在
paintComponent方法中,而非直接在main中调用。






