将指针位置传递给Java中的对象

时间:2010-03-23 00:45:11

标签: java oop

我有一个名为Board的JPanel类,它带有一个静态子类MouseHanlder,它跟踪Board中相应监听器的鼠标位置。我的Board类有字段pointerX和pointerY。

如何将e.getX()和e.getY()从MouseHandler子类传递给它的超类JPanel?我尝试使用getter,setter,super,并且无法在子类和父类之间进行数据传输。我确定这是一个概念问题,但我陷入困境。

谢谢!

由于受欢迎的需求,一些代码。这是没有任何传递的代码:

public class Board extends JPanel {


int x; // Mouse pointer fields.
int y;

public Board() {

            blah blah

    MouseHandler handler = new MouseHandler();
    addMouseMotionListener(handler);

}


static class MouseHandler implements MouseMotionListener {
    int pointerX;
    int pointerY;

    public void mouseMoved(MouseEvent e) {

             i'd like to do something like:
                 super.x = e.getX();
                 super.x = e.getY();

                 or

                 Board.setX() = e.getX(); // Missing setters below, this is just an example.
                 Board.setX() = e.getY();




    }

}

}

3 个答案:

答案 0 :(得分:2)

这是因为您的类的静态实现没有看到您的jpanel实例。您可以将引用传递给MouseAdapter(或MouseListener

class MyPanel extends JPanel
{
  MyPanel()
  {
    item.addMouseListener(new MyListener(this));
  }

  void pass(int x, int y)
  {
    //whatever
  }

  class MyListener extends MouseAdapter
  {
    MyPanel ref;

    MyListener(MyPanel ref)
    {
      this.ref = ref;
    }

    public void mousePressed(MouseEvent e)
    {
      ref.pass(e.getX(), e.getY());
    }
  }
}

答案 1 :(得分:1)

简单。执行一个e.getSource(),它将为您提供事件发生的源。在你的情况下,它将是你的董事会课程。只需将实例强制转换为Board实例即可。

public class Board extends JPanel {


int x; // Mouse pointer fields.
int y;

public Board() {

            blah blah

    MouseHandler handler = new MouseHandler();
    addMouseMotionListener(handler);

}


static class MouseHandler implements MouseMotionListener {
    int pointerX;
    int pointerY;

    public void mouseMoved(MouseEvent e) {
       Board b = (Board) e.getSource();
       b.setX(e.getX()); 
       b.setY(e.getY());
    }

}
}

答案 2 :(得分:0)

这是一种方式。此技术使用对MouseHandler的外部类的隐式引用:

public class Board extends JPanel {

    public Board() {
        addMouseListener(new MouseHandler());
    }

    private void doSomething(int x, int y) {
        // ...
    }

    private final class MouseHandler extends MouseAdapter {
        public void mouseMoved(MouseEvent e) {
            Board.this.doSomething(e.getX(), e.getY());
        }        
    };
}