Java - 选择和移动对象

时间:2016-03-09 13:48:19

标签: java

我想基本上选择框架上的一个对象然后拖动它,然后用鼠标移动对象。出于某种原因,我似乎无法让它发挥作用。

这是我的代码压缩方法:

 public void mousePressed(MouseEvent event)
 {
    //Get x and y
    int x = event.getX();
    int y = event.getY();
    //set selected to null
    selected = null;
    //if a fruit contains x, y then selected is assigned that fruit
    for( Fruit m : fruits)
        {
        if(m.contains(x,y))
            {
            selected.setXY(x,y);
            }
        }

这是我的拖拽方法:

 public void mouseDragged(MouseEvent event)
 {
     //if selected not equal null
     if(selected != null){
        //get x and y
        int x = event.getX();
        int y = event.getY();
        //make select follow the mouse and repaint
        selected.setXY(x,y);
        repaint();
   }
  }

如果您需要更多我的代码,请告诉我,我会编辑问题并添加。

感谢任何帮助

1 个答案:

答案 0 :(得分:1)

由于您将selected设置为null,因此无效。

如果将mousePressed更改为会发生什么(请注意,只有在(x,y)处只有一个水果时才会有效:

 public void mousePressed(MouseEvent event)
 {
    //Get x and y
    int x = event.getX();
    int y = event.getY();
    //set selected to null
    selected = null;
    //if a fruit contains x, y then selected is assigned that fruit
    for( Fruit m : fruits)
    {
       if(m.contains(x,y))
       {
         selected = m;
         // position is set in mouseDrag
       }
    }

在mouseReleased中,然后将selected设置为null(可选)。