tags:

views:

55

answers:

3

I've got a JPanel class called Board with a static subclass, MouseHanlder, which tracks the mouse position along the appropriate listener in Board. My Board class has fields pointerX and pointerY.

How do i pass the e.getX() and e.getY() from the MouseHandler subclass to its super class JPanel? I tried with getters, setters, super, and cant get the data transfer between subclass and parent class. I'm certain it's a concept issue, but im stuck.

Thanks!

Due popular demand, some code. This is the code without any atempt of passing :

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();




    }

}

}

+2  A: 

This because your static implementation of the class doesn't see your jpanel instance. You can do it passing a reference to the MouseAdapter (or 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());
    }
  }
}
Jack
+1  A: 

Simple. Do an e.getSource() which will give you the source on which the event occurred. In your case it will be your Board class. Simply cast the instance to a Board instance and you are set.

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());
    }

}
}
Savvas Dalkitsis
A: 

Here's one way. This technique uses the implicit reference to the outer class of 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());
        }        
    };
}
harto