杰瑞科技汇

Java中fillPolygon方法如何使用?

Of course! The fillPolygon method in Java is a fundamental part of the 2D graphics API, used to draw a filled polygon on a screen. It's part of the java.awt.Graphics and java.awt.Graphics2D classes.

Java中fillPolygon方法如何使用?-图1
(图片来源网络,侵删)

Here's a comprehensive guide covering everything from the basic concept to practical examples.

What is fillPolygon?

The fillPolygon method takes a set of coordinates (points) and connects them to form a polygon, then fills the interior of that shape with the current color set in the Graphics context.

There are two main overloaded versions of this method:

  1. fillPolygon(int[] xPoints, int[] yPoints, int nPoints): This is the most common version. You provide two separate arrays for the x and y coordinates of the vertices, and the total number of points.
  2. fillPolygon(Polygon p): This version takes a java.awt.Polygon object as an argument. This is often cleaner as it encapsulates the polygon's data and its own drawing logic.

Method Signatures

Version 1: Using Separate Arrays

// In java.awt.Graphics and java.awt.Graphics2D
public abstract void fillPolygon(int[] xPoints, int[] yPoints, int nPoints);
  • xPoints: An array of x-coordinates.
  • yPoints: An array of y-coordinates.
  • nPoints: The total number of points in the polygon. This must be the same for both arrays and must be at least 3 to form a valid polygon.

Version 2: Using a Polygon Object

// In java.awt.Graphics and java.awt.Graphics2D
public abstract void fillPolygon(Polygon p);
  • p: An instance of the java.awt.Polygon class, which contains the points of the polygon.

The java.awt.Polygon Class

Using the Polygon class is often recommended because it's more object-oriented.

Java中fillPolygon方法如何使用?-图2
(图片来源网络,侵删)

Key Methods of Polygon:

  • Polygon(): Creates an empty polygon.
  • addPoint(int x, int y): Adds a vertex to the polygon.
  • npoints: An attribute that stores the number of points in the polygon.
  • xpoints: An attribute that stores the array of x-coordinates.
  • ypoints: An attribute that stores the array of y-coordinates.

Step-by-Step Example (Using Separate Arrays)

This example demonstrates how to draw a simple filled triangle in a Swing JPanel.

DrawingPanel.java

import javax.swing.*;
import java.awt.*;
public class DrawingPanel extends JPanel {
    @Override
    protected void paintComponent(Graphics g) {
        // It's good practice to call the parent's paintComponent method
        super.paintComponent(g);
        // 1. Set the fill color
        g.setColor(Color.BLUE);
        // 2. Define the coordinates of the polygon's vertices
        //    We'll draw a triangle
        int[] xPoints = { 50, 150, 100 }; // x-coordinates of the three corners
        int[] yPoints = { 200, 200, 50 };  // y-coordinates of the three corners
        int nPoints = 3;                  // Number of vertices
        // 3. Draw the filled polygon
        g.fillPolygon(xPoints, yPoints, nPoints);
        // Let's draw another one with a different color
        g.setColor(new Color(255, 100, 100)); // A coral-like color
        int[] xPoints2 = { 200, 300, 250 };
        int[] yPoints2 = { 100, 100, 50 };
        g.fillPolygon(xPoints2, yPoints2, 3);
    }
}

MainApplication.java

import javax.swing.JFrame;
public class MainApplication {
    public static void main(String[] args) {
        // Create a new JFrame (window)
        JFrame frame = new JFrame("Java fillPolygon Example");
        // Create an instance of our drawing panel
        DrawingPanel panel = new DrawingPanel();
        // Add the panel to the frame
        frame.add(panel);
        // Set the size of the window
        frame.setSize(400, 300);
        // Ensure the application closes when the window is closed
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // Center the window on the screen
        frame.setLocationRelativeTo(null);
        // Make the window visible
        frame.setVisible(true);
    }
}

To run this:

  1. Save both files in the same directory.
  2. Compile them: javac DrawingPanel.java MainApplication.java
  3. Run the main application: java MainApplication

You will see a window with a blue triangle and a red triangle.

Java中fillPolygon方法如何使用?-图3
(图片来源网络,侵删)

Step-by-Step Example (Using the Polygon Class)

This example achieves the same result but demonstrates the Polygon class approach, which is more scalable.

DrawingPanelWithPolygon.java

import javax.swing.*;
import java.awt.*;
public class DrawingPanelWithPolygon extends JPanel {
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        // 1. Create a Polygon object
        Polygon triangle = new Polygon();
        // 2. Add points to the polygon
        triangle.addPoint(50, 200);
        triangle.addPoint(150, 200);
        triangle.addPoint(100, 50);
        // 3. Set the fill color
        g.setColor(Color.GREEN);
        // 4. Draw the filled polygon using the Polygon object
        g.fillPolygon(triangle);
        // You can easily reuse the polygon object or create new ones
        Polygon anotherShape = new Polygon();
        anotherShape.addPoint(200, 100);
        anotherShape.addPoint(300, 100);
        anotherShape.addPoint(250, 50);
        anotherShape.addPoint(220, 150); // A quadrilateral
        g.setColor(new Color(150, 50, 200)); // Purple-ish
        g.fillPolygon(anotherShape);
    }
}

You would create a MainApplication similar to the one above, but it would instantiate DrawingPanelWithPolygon instead. The result will be a green triangle and a purple quadrilateral.


Key Considerations

a. Non-Convex and Complex Polygons

The fillPolygon method is smart enough to handle non-convex polygons (polygons with "dents") and even self-intersecting polygons. It uses an "even-odd" fill rule to determine the interior.

Example of a non-convex polygon (a star):

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.ORANGE);
    int[] xPoints = { 100, 120, 200, 130, 150 };
    int[] yPoints = { 50, 150, 150, 100, 100 };
    g.fillPolygon(xPoints, yPoints, 5);
}

b. Graphics2D and Rendering Hints

For better control over the appearance of your graphics, it's best to use Graphics2D. You can cast the Graphics object passed to paintComponent.

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    // Cast to Graphics2D for more advanced features
    Graphics2D g2d = (Graphics2D) g;
    // Enable anti-aliasing for smoother edges
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setColor(Color.MAGENTA);
    int[] xPoints = { 50, 100, 150, 100 };
    int[] yPoints = { 100, 50, 100, 150 };
    g2d.fillPolygon(xPoints, yPoints, 4);
}

c. Polygon Validation

  • A polygon must have at least 3 points. If you provide fewer, fillPolygon will likely do nothing or throw an exception.
  • If the points are collinear (all on the same line), the "polygon" will have no area and will not be visible.
分享:
扫描分享到社交APP
上一篇
下一篇