有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在JPanel上捕捉多边形

我正在尝试制作一个地图编辑器,它支持不同角度的矩形(因此它使用多边形绘制矩形)。我想通过多边形在帧上的位置捕捉多边形,而不使用数学计算

有命令支持这样的事情吗

我试图通过多边形的视觉表示捕捉它们:

public void mousePressed(MouseEvent e){
 Component component = getComponentAt(e.getX(), e.getY());
  if(component instanceof wall){

但它不起作用

(如果我只是画矩形,我会使用JPanel和setbounds命令来画矩形,但我认为我不能画多边形形状的JPanel)


共 (2) 个答案

  1. # 1 楼答案

    您不会使用单独的JPanel来绘制每个多边形。您可以使用一个扩展JPanel的类,然后重写paintComponent()方法来绘制多边形。更多信息here

    将多边形绘制到JPanel后,可以使用多边形。contains()方法来测试鼠标是否在JPanel中。有关这方面的更多信息,请参见the API

  2. # 2 楼答案

    首先需要创建一个包含要绘制的所有多边形的列表:

    Shape circle = new Ellipse2D.Double(0, 0, 30, 30);
    List<Shape> shapes = new ArrayList<Shape>();
    shapes.add( circle );
    

    然后在paintComponent()方法中,遍历列表中的所有形状:

    Graphics2D g2d = (Graphics2D)g.create();
    
    for (Shape shape : shapes)
    {
        g2d.draw( shape );
    }
    
    g2d.dispose();
    

    然后在MouseListener中遍历列表,查看单击了哪个形状:

    public void mousePressed(MouseEvent e)
    {
        for (Shape shape : shapes)
        {
            if (shape.contains(e.getPoint())
                // do something
        }
    
    }
    

    If i was simply drawing rectangles i would use JPanel and use setbounds command to draw a rectangle, but i dont think i can make polygon-shaped JPanels

    对于使用组件的替代方法,请检查Playing With Shapes。那里的类允许您使用任何形状创建ShapeComponent