【问题标题】:How do i remove an object from an array list after a mouse event?鼠标事件后如何从数组列表中删除对象?
【发布时间】:2014-11-10 05:34:38
【问题描述】:

当我在 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) {}
   }
}

【问题讨论】:

  • pointList.contains(event.getPoint()) - 如果 arraylist 包含该值,则返回 true,否则返回 false

标签: java arrays loops object jpanel


【解决方案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();
  }

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 2020-02-11
    相关资源
    最近更新 更多