java中drawpolyline
时间: 2023-07-25 19:18:52 浏览: 44
`drawPolyline` 是 Java 2D API 中用于绘制折线的方法。它的语法如下:
```java
public void drawPolyline(int[] xPoints, int[] yPoints, int nPoints)
```
其中,`xPoints` 和 `yPoints` 分别是折线上每个点的横坐标和纵坐标组成的数组,`nPoints` 是折线上点的数量。
使用 `drawPolyline` 方法可以方便地绘制多个点组成的折线。例如,下面的代码绘制了一个三角形:
```java
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PolylineExample extends JPanel {
private int[] xPoints = {100, 150, 200};
private int[] yPoints = {100, 150, 100};
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.drawPolyline(xPoints, yPoints, 3);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Polyline Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.add(new PolylineExample());
frame.setVisible(true);
}
}
```
在这个示例中,我们重写了 `JPanel` 的 `paintComponent` 方法,使用 `drawPolyline` 方法绘制了一个三角形。注意,`drawPolyline` 方法只是将所有点连接起来,并不会自动将折线首尾相接形成一个封闭图形。如果需要绘制一个封闭图形,需要将起点和终点重复添加到坐标数组中。