请给出java边界标志算法绘制多边形的代码
时间: 2024-06-10 18:06:31 浏览: 122
以下是Java中实现边界标志算法绘制多边形的代码:
```java
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class PolygonDrawer extends JFrame {
private ArrayList<Point> points;
private int mouseX, mouseY;
private boolean mouseDown = false;
private boolean firstPoint = true;
public PolygonDrawer() {
super("Polygon Drawer");
setSize(640, 480);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create the list to hold the points
points = new ArrayList<Point>();
// add the mouse listener for the drawing area
JPanel panel = new JPanel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
drawPolygon(g);
}
};
panel.setBackground(Color.WHITE);
panel.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
mouseDown = true;
if (firstPoint) {
points.add(new Point(mouseX, mouseY));
firstPoint = false;
}
}
public void mouseReleased(MouseEvent e) {
mouseDown = false;
}
});
panel.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
repaint();
}
public void mouseDragged(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
if (mouseDown) {
points.add(new Point(mouseX, mouseY));
repaint();
}
}
});
getContentPane().add(panel);
setVisible(true);
}
public static void main(String[] args) {
new PolygonDrawer();
}
private void drawPolygon(Graphics g) {
if (points.size() > 0) {
int[] xPoints = new int[points.size()];
int[] yPoints = new int[points.size()];
for (int i = 0; i < points.size(); i++) {
xPoints[i] = points.get(i).x;
yPoints[i] = points.get(i).y;
}
g.drawPolygon(xPoints, yPoints, points.size());
}
if (mouseDown) {
if (points.size() > 0) {
int[] xPoints = new int[points.size() + 1];
int[] yPoints = new int[points.size() + 1];
for (int i = 0; i < points.size(); i++) {
xPoints[i] = points.get(i).x;
yPoints[i] = points.get(i).y;
}
xPoints[points.size()] = mouseX;
yPoints[points.size()] = mouseY;
g.drawPolyline(xPoints, yPoints, points.size() + 1);
} else {
g.drawLine(mouseX, mouseY, mouseX, mouseY);
}
}
}
}
```
希望对你有帮助!
阅读全文