You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaFX中Polygon.contains仅识别边上点而非内部点的原因排查

问题:JavaFX Polygon.contains() 仅识别边上点,内部点未被检测到

我编写了一个JavaFX程序,功能是当点位于多边形内部时将对应位置的圆形标记为红色。但实际运行发现,Polygon.contains()方法仅在点处于多边形的边上时返回true,内部点未被识别。附上完整代码:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Polygon;
import javafx.stage.Stage;

public class Testing extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        Pane pane = new Pane();

        //Set up polygon
        Polygon polygon1 = new Polygon(30.0, 30.0, 100.0, 3.0, 100.0, 130.0, 60.0, 60.0, 3.0, 100.0, 30.0, 30.0);
        polygon1.setFill(null);
        polygon1.setStroke(Color.BLACK);

        //set up circles
        Circle[] circles = new Circle[26];
        int counter = 0;
        for (int x = 0; x < 130; x+=30) {
            for (int y = 0; y < 130; y+=30) {
                circles[counter] = new Circle(x, y, 4);

                //if circle is inside polygon, color it red
                if (polygon1.contains(x, y)) {
                    circles[counter].setFill(Color.RED);
                }

                pane.getChildren().add(circles[counter]);
                counter++;
            }
        }

        pane.getChildren().addAll(polygon1);

        Scene scene = new Scene(pane, 130, 130);
        primaryStage.setTitle("Exercise14_20");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

我已尝试用Rectangle替代Polygon、使用ObservableList存储多边形顶点、打印contains的判断结果,但问题依旧,请问这是为什么?


原因及解决方案

问题根源

你的多边形存在两个关键问题:

  1. 顶点重复:最后一个顶点重复了第一个点(30.0, 30.0),虽然Polygon会自动闭合首尾,但手动重复可能干扰区域计算;
  2. 顶点顺序错误:顶点排列出现了自相交,导致JavaFX使用的奇偶规则在计算内部区域时出现抵消,大部分内部点被判定为外部。

修复步骤

  1. 移除重复的最后一个顶点;
  2. 调整顶点顺序为顺时针或逆时针的连续排列,避免自相交。

修改后的多边形代码

// 修正为逆时针连续排列的顶点,无重复
Polygon polygon1 = new Polygon(30.0, 30.0, 100.0, 3.0, 100.0, 130.0, 3.0, 100.0, 60.0, 60.0);

验证方法

可以给Polygon设置一个非透明填充色(比如polygon1.setFill(Color.LIGHTBLUE)),直观查看填充区域是否符合预期。如果填充区域和你肉眼看到的多边形轮廓一致,说明顶点顺序正确,此时contains()方法就能正常识别内部点了。

内容的提问来源于stack exchange,提问作者JNowata63

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 05:01:25