杰瑞科技汇

Java fillPolygon如何填充自定义多边形?

Of course! The fillPolygon method in Java is a fundamental part of the java.awt.Graphics and java.awt.Graphics2D classes. It's used to draw a filled polygon on a component, like a JFrame or JPanel.

Java fillPolygon如何填充自定义多边形?-图1
(图片来源网络,侵删)

Let's break it down, starting with the basics and moving to more complete, runnable examples.

The Core Concept

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

The Method Signatures

There are three main ways to call fillPolygon:

a) Using Two Integer Arrays

This is the most common approach. You provide separate arrays for the x-coordinates and y-coordinates.

Java fillPolygon如何填充自定义多边形?-图2
(图片来源网络,侵删)
// Signature
void fillPolygon(int[] xPoints, int[] yPoints, int nPoints);
// Parameters:
// - xPoints: An array of x-coordinates.
// - yPoints: An array of y-coordinates.
// - nPoints: The total number of points to use from the arrays.

Important: The xPoints and yPoints arrays must have at least nPoints elements, and nPoints must be at least 3.

b) Using a Polygon Object

This is often a cleaner approach, especially if you plan to manipulate the polygon (e.g., translate, rotate). You first create a java.awt.Polygon object, add points to it, and then pass that object to the method.

// Signature
void fillPolygon(Polygon p);
// Parameters:
// - p: The Polygon object to be filled.

c) Using Arrays of Point Objects (for Graphics2D)

If you are using the modern Graphics2D class (which you almost always should be), there's a convenient overload that takes an array of java.awt.Point objects.

// Signature (in Graphics2D)
void fillPolygon(Point[] points);
// Parameters:
// - points: An array of Point objects.

Simple Example: Drawing a Triangle

This is the most basic example. We'll create a JPanel and override its paintComponent method to draw a filled triangle.

Java fillPolygon如何填充自定义多边形?-图3
(图片来源网络,侵删)

TriangleExample.java

import javax.swing.*;
import java.awt.*;
public class TriangleExample extends JPanel {
    @Override
    protected void paintComponent(Graphics g) {
        // Always call the superclass's paintComponent method first
        super.paintComponent(g);
        // Cast to Graphics2D for better rendering quality (optional but recommended)
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        // Define the vertices of the triangle
        int[] xPoints = {50, 150, 100}; // x-coordinates of the three points
        int[] yPoints = {150, 150, 50};  // y-coordinates of the three points
        // Set the fill color
        g2d.setColor(Color.GREEN);
        // Draw the filled polygon
        g2d.fillPolygon(xPoints, yPoints, 3); // 3 is the number of points
    }
    public static void main(String[] args) {
        // Create a new JFrame
        JFrame frame = new JFrame("Java fillPolygon Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(250, 250);
        // Create an instance of our custom JPanel
        TriangleExample panel = new TriangleExample();
        // Add the panel to the frame
        frame.add(panel);
        // Make the frame visible
        frame.setVisible(true);
    }
}

How to Run:

  1. Save the code as TriangleExample.java.
  2. Compile it: javac TriangleExample.java
  3. Run it: java TriangleExample

You will see a window with a green triangle.


Advanced Example: Drawing a Star

This example demonstrates how to draw a more complex shape. We'll use the Polygon object, which is very useful for creating multi-point shapes.

StarExample.java

import javax.swing.*;
import java.awt.*;
import java.awt.geom.Point2D;
public class StarExample extends JPanel {
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        // Create a Polygon object
        Polygon star = new Polygon();
        // Define the points of a 5-pointed star
        int centerX = getWidth() / 2;
        int centerY = getHeight() / 2;
        int outerRadius = 80;
        int innerRadius = 40;
        int numPoints = 5;
        for (int i = 0; i < numPoints * 2; i++) {
            double angle = Math.toRadians(i * 180.0 / numPoints);
            int radius = (i % 2 == 0) ? outerRadius : innerRadius;
            // Calculate x and y coordinates
            int x = (int) (centerX + radius * Math.cos(angle - Math.PI / 2));
            int y = (int) (centerY + radius * Math.sin(angle - Math.PI / 2));
            // Add the point to the polygon
            star.addPoint(x, y);
        }
        // Set the fill color
        g2d.setColor(Color.ORANGE);
        // Draw the filled polygon using the Polygon object
        g2d.fillPolygon(star);
    }
    public static void main(String[] args) {
        JFrame frame = new JFrame("Star with fillPolygon");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(250, 250);
        StarExample panel = new StarExample();
        frame.add(panel);
        frame.setVisible(true);
    }
}

How to Run:

  1. Save as StarExample.java.
  2. Compile: javac StarExample.java
  3. Run: java StarExample

This will produce an orange star.


Key Considerations and Best Practices

  1. Always Use paintComponent: When drawing on Swing components, you should always override the paintComponent method, not paint. This ensures that the component's background and children are painted correctly.

  2. Call super.paintComponent(g): The first line inside your paintComponent method should almost always be super.paintComponent(g);. This is crucial for the Swing painting system to function properly.

  3. Use Graphics2D: For any serious graphics work, cast the Graphics object to Graphics2D. Graphics2D provides more powerful features like anti-aliasing, transformations (rotation, scaling), and better control over strokes and fills.

  4. Define Colors First: The color you set with setColor() is used for all subsequent drawing operations until you change it again. Make sure you set the fill color before you call fillPolygon.

  5. Polygon vs. Arrays: Use the two-array method for simple, one-off polygons. Use the Polygon object if you need to reuse the shape, add points dynamically, or apply transformations to it.

  6. Closed Shape: The fillPolygon method automatically closes the shape. If your last point is not the same as your first, it will draw a line from the last point back to the first to complete the polygon before filling it.

分享:
扫描分享到社交APP
上一篇
下一篇