Re: Passing a mouse event message to the parent window?
If anyone is curious, here's how I finally figured out to make it work.
This change allows you to drag and drop a button (or any other
Component) anywhere in the parent window with the mouse. Notice that
when the mouse event is passed to the parent the x,y coordinates need
to be transformed from relative to the button to relative to the
parent.
In the code above replace the three lines:
--------------
// Create a button.
dragButton = new JButton("Drag Me");
parent.add(dragButton);
-------------
With:
-------------
// Create a button.
dragButton = new JButton("Drag Me");
dragButton.addMouseListener( new MouseListener() {
public void mousePressed(MouseEvent e) {
if ( disabled ) {
int newX = e.getX() + dragButton.getX();
int newY = e.getY() + dragButton.getY();
MouseEvent transformed =
new MouseEvent(dragButton,
MouseEvent.MOUSE_PRESSED, e.getWhen(),
0, newX, newY, e.getClickCount(), false,
e.getButton());
parent.dispatchEvent( transformed );
}
}
public void mouseReleased(MouseEvent e) {
if ( disabled ) {
int newX = e.getX() + dragButton.getX();
int newY = e.getY() + dragButton.getY();
MouseEvent transformed =
new MouseEvent(dragButton,
MouseEvent.MOUSE_RELEASED, e.getWhen(),
0, newX, newY, e.getClickCount(), false,
e.getButton());
parent.dispatchEvent( transformed );
}
}
public void mouseExited(MouseEvent e) {} // do nothing
public void mouseEntered(MouseEvent e) {} // do nothing
public void mouseClicked(MouseEvent e) {} // do nothing
});
dragButton.addMouseMotionListener( new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
if ( disabled ) {
int newX = e.getX() + dragButton.getX();
int newY = e.getY() + dragButton.getY();
MouseEvent transformed =
new MouseEvent(dragButton,
MouseEvent.MOUSE_DRAGGED, e.getWhen(),
0, newX, newY, e.getClickCount(), false,
e.getButton());
parent.dispatchEvent( transformed );
}
}
public void mouseMoved(MouseEvent e) {} //do nothing
});
parent.add(dragButton);
---------------
--gary