有 Java 编程相关的问题?

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

java如何在鼠标事件后从数组列表中删除对象?

当我在JPanel中单击鼠标时,程序会创建一个绿点,并在屏幕上显示一个点数计数器。这些点位于保存为对象的数组列表中。我试图修改这个代码,这样如果我在现有点(每个点的半径为6)的半径内单击,该点将从列表中消失,并从屏幕上删除

(在你问之前,是的,你可能会意识到这是一个家庭作业问题,不,我不是想作弊)

我认为这需要创建一个for循环来扫描数组中的对象,寻找指针可能点击过的对象。然而,我很困惑,到底该如何做到这一点

谢谢

public class DotsPanel extends JPanel
{
   private final int SIZE = 6;  // radius of each dot

   private ArrayList<Point> pointList;// "Point"s are objects that rep. the x & y coordinates of a dot





   public DotsPanel()
   {
      pointList = new ArrayList<Point>();

      addMouseListener (new DotsListener());

      setBackground(Color.black);
      setPreferredSize(new Dimension(300, 200));
   }




   public void paintComponent(Graphics page)
   {
      super.paintComponent(page);

      page.setColor(Color.green);

      for (Point spot : pointList)
         page.fillOval(spot.x-SIZE, spot.y-SIZE, SIZE*2, SIZE*2);



      page.drawString("Count: " + pointList.size(), 5, 15);//draws the image of the counter




   }




   private class DotsListener implements MouseListener
   {


      public void mousePressed(MouseEvent event)
      {
         pointList.add(event.getPoint());
         repaint();
      }


      public void mouseClicked(MouseEvent event) {}
      public void mouseReleased(MouseEvent event) {}
      public void mouseEntered(MouseEvent event) {}
      public void mouseExited(MouseEvent event) {}
   }
}

共 (1) 个答案

  1. # 1 楼答案

    显然,您需要在DotsListener中修改mousePressed()的实现,因为您不希望在每次单击时无条件地添加一个新点。我建议改成这样:

      public void mousePressed(MouseEvent event)
      {
         Point hitDot = getHitDot(event);
         if (hitDot == null) {
             // no dots hit
             pointList.add(event.getPoint());
         } else {
             // hit a dot
             pointList.remove(hitDot);
         }
         repaint();
      }
    

    既然这是家庭作业,我就不给你写了。我会说你的想法是正确的:循环遍历pointList的所有元素,测试每个Point,如果在距离鼠标按下坐标SIZE的范围内,立即返回它。可以使用Euclidean distance公式对每个点进行命中测试