Shape position wont redraw when dragged with mouse - java

I have a filled circle drawn on a canvas and I'm trying to get it to move based on a click and drag method with the mouse. I've managed to checked whether the mouse pointer is within the bounds of the circle, and when I drag the mouse, the variable storing the position of the circle updates as it should, but the circle itself is not redrawing as I'm dragging (the most it will do is flicker). My problem is at the end where I'm overriding mouseDragged().
getCanvas().addMouseListener(new MouseAdapter()
{
#Override
public void mouseClicked(MouseEvent event)
{
super.mouseClicked(event);
Point mousePosition = event.getPoint();
if (_circle.getShape1().contains(mousePosition))
Main.debugLabel.setText("Clicked");
}
#Override
public void mouseReleased(MouseEvent event)
{
super.mouseReleased(event);
_circle.isDraggable = false;
Main.debugLabel.setText("Released");
}
#Override
public void mousePressed(MouseEvent event)
{
super.mousePressed(event);
int button = event.getModifiers();
if (button == InputEvent.BUTTON1_MASK)
{
_circle.isDraggable = true;
Main.debugLabel.setText("Pressed");
}
}
});
getCanvas().addMouseMotionListener(new MouseAdapter()
{
#Override
public void mouseDragged(MouseEvent event)
{
super.mouseDragged(event);
Point mousePosition = event.getPoint();
if (_circle.isDraggable)
{
_circle.posX = mousePosition.x;
_circle.posY = mousePosition.y;
Main.debugLabel.setText("Dragging " + _circle.posX);
getCanvas().repaint();
}
}
#Override
public void mouseMoved(MouseEvent event)
{
super.mouseMoved(event);
Point mousePosition = event.getPoint();
if (_circle.getShape1().contains(mousePosition))
Main.debugLabel.setText("Within Bounds");
else if (!_circle.getShape1().contains(mousePosition) && !_circle.isDraggable)
Main.debugLabel.setText("Out of Bounds");
}
});

As shown in this example, one approach is to maintain two Point instances. One holds the last mouse location; the other holds the desired target location; both are in in component-relative coordinates.
In mousePressed(),
Initialize the last mouse location.
Optionally, mark the target as selected.
Invoke repaint() to display the selected appearance.
In mouseDragged(),
Update the target location by the difference between the new and old mouse locations.
Update the last mouse location to the current mouse location.
Invoke repaint().

Related

How can I difference if a component has been dragged or clicked?

I have a JPanel with many JButton components inside. Is there a way to get the panel mouse event when a button is pressed? Another point of view: How to make button transparent to panel mouse event? I specifically need to capture mousePressed() event of panel.
EDIT
Context:
I'm dragging the panel content through a JScrollPane (actually working), to accomplish that I needed to capture the point where mouse is pressed, so both panel and buttons have MouseListener and MouseMotionListener to capture the point and do other stuff.
Issue:
When I press -> drag -> release the mouse button, if the mouse is still over the button it executes whatever the button does. So I want the mouse listener of the panel to be 'independent' of the button, to remove the mouse listener from the buttons.
EDIT 2
I just realize reading my own issue... that it will make no difference removing MouseListener to the JButton. When pressing the button if the mouse it stil over it, the actionPerformed will be executed anyway...What can I do?
EDIT 3
Edited question title, according to the solution.
Kipping in mind that the event execution order in this case is: mousePressed->mouseDragged->actionPerformed->mouseReleased , I get it working at the moment, adding a boolean:
#Override
public void mousePressed(MouseEvent e) {
origin = new Point(e.getPoint());
}
//each time the user stops dragging set dragged to false
#Override
public void mouseReleased(MouseEvent arg0) {
dragged = false;
}
#Override
public void mouseDragged(MouseEvent e) {
dragged=true;
if(((Component) e.getSource()).getParent().equals(myPanel)
|| e.getSource().equals(myPanel)){
if (origin != null) {
JViewport viewPort = (JViewport) SwingUtilities.getAncestorOfClass(JViewport.class, myPanel);
if (viewPort != null) {
int deltaX = origin.x - e.getX();
int deltaY = origin.y - e.getY();
Rectangle view = viewPort.getViewRect();
view.x += deltaX;
view.y += deltaY;
myPanel.scrollRectToVisible(view);
}
}
}
#Override
public void actionPerformed(ActionEvent e){
//stuff do detect the button...
//..in case there is more than one panel, if the component belong to myPanel and dragg is false
if(((Component) e.getSource()).getParent().equals(myPanel)&& dragged==false ){
//do stuff
}
}

Java, If a draggable object touches other object

I have a code for dragging a label width mouse.
lbl_banner.addMouseListener(new MouseAdapter()
{
#Override
public void mousePressed(MouseEvent e) {
//catching the current values for x,y coordinates on screen
x_pressed = e.getX();
y_pressed = e.getY();
}
});
lbl_banner.addMouseMotionListener(new MouseMotionAdapter(){
#Override
public void mouseDragged(MouseEvent e){
//and when the Jlabel is dragged
setLocation(e.getXOnScreen() - x_pressed, e.getYOnScreen() - y_pressed);
}
});
Now, how do I make a function: While I'm dragging this label around the Screen, If the Label by dragging touches other object (label, button,...) to do something.
if(//labelTouchesSomething){//do something}
While this is not technically a dragging but the dynamic move of a component (dragging is the transfer of contents in between components), you can compute the intersection of the current moving component against other components (this may need some navigation inside your hierarchy). May be this can help you: How do I detect the collison of components?. You can also use the methods contains of Component to determine if some coordinates are inside a component or not.

Animation - irregular working of MouseListener

In my animation one of elements is moving oval. There are two ways to control it. The first is setting x,y position by mouse listener and the second is Key Listener. During first using animation both methods work. But after using stop (clear) button mouse listener doesn't work, but Key method is still working.
Code stop method:
void clear() {
waves.clear();
xz_list.clear();
yz_list.clear();
time_list.clear();
f_list.clear();
time=0;
timer.stop();
repaint();
}
MouseListener method:
void SourcePosition(double v, String d) {
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
{
x_o = e.getX();
y_o = e.getY();
repaint();
}
}
});
}
Generally this is application showing Doppler Effect. Start button make setting data from interface, disable interface and start animation and chart. Stop button uses clear() method and enable interface.

Java: Restrict the mouse movement to vertical

Is there a way to restrict the mouse movement to vertical? I am currently developing a program when user dragging mouse pointer to the left or right in specific rectangle shape cursor can't move but up and down movements should work.
you can try like this,f is reference to a Jframe but here the X co-ordinate is fixed.
final Robot r=new Robot();
f.addMouseMotionListener(new MouseMotionListener(){
#Override
public void mouseDragged(MouseEvent e) {
}
#Override
public void mouseMoved(MouseEvent e) {
r.mouseMove(20, e.getY());
}
});

Making a component less sensitive to Dragging in Swing

A JComponent of mine is firing a mouseDragged event too vigorously. When the user is trying to click, it interprets is as a drag even if the mouse has only moved 1 pixel.
How would I add a rule for a particular component that amounted to:
Do not consider it a drag event unless
the mouse has moved 10 pixels from the
point at which is was pressed down.
Note: I know it's not a system setting in my OS, since only events on that component suffer from this over sensitivity.
Thank you.
Previous answers combined together, with proper event type:
public class DragInsensitiveMouseClickListener implements MouseInputListener {
protected static final int MAX_CLICK_DISTANCE = 15;
private final MouseInputListener target;
public MouseEvent pressed;
public DragInsensitiveMouseClickListener(MouseInputListener target) {
this.target = target;
}
#Override
public final void mousePressed(MouseEvent e) {
pressed = e;
target.mousePressed(e);
}
private int getDragDistance(MouseEvent e) {
int distance = 0;
distance += Math.abs(pressed.getXOnScreen() - e.getXOnScreen());
distance += Math.abs(pressed.getYOnScreen() - e.getYOnScreen());
return distance;
}
#Override
public final void mouseReleased(MouseEvent e) {
target.mouseReleased(e);
if (pressed != null) {
if (getDragDistance(e) < MAX_CLICK_DISTANCE) {
MouseEvent clickEvent = new MouseEvent((Component) pressed.getSource(),
MouseEvent.MOUSE_CLICKED, e.getWhen(), pressed.getModifiers(),
pressed.getX(), pressed.getY(), pressed.getXOnScreen(), pressed.getYOnScreen(),
pressed.getClickCount(), pressed.isPopupTrigger(), pressed.getButton());
target.mouseClicked(clickEvent);
}
pressed = null;
}
}
#Override
public void mouseClicked(MouseEvent e) {
//do nothing, handled by pressed/released handlers
}
#Override
public void mouseEntered(MouseEvent e) {
target.mouseEntered(e);
}
#Override
public void mouseExited(MouseEvent e) {
target.mouseExited(e);
}
#Override
public void mouseDragged(MouseEvent e) {
if (pressed != null) {
if (getDragDistance(e) < MAX_CLICK_DISTANCE) return; //do not trigger drag yet (distance is in "click" perimeter
pressed = null;
}
target.mouseDragged(e);
}
#Override
public void mouseMoved(MouseEvent e) {
target.mouseMoved(e);
}
}
I've had to do exactly this before. Here's my mouse event processing code, cut down to just the bits relating to making drag require a few pixels before being treated as a drag.
public void mousePressed(int mod, Point loc) {
pressLocation=copyLocation(loc,pressLocation);
dragLocation=null;
}
public void mouseReleased(int mod, Point loc) {
if(pressLocation!=null && dragLocation!=null) {
// Mouse drag reverted to mouse click - not dragged far enough
// action for click
pressLocation=null;
}
else if(dragLocation!=null) {
// action for drag completed
}
else {
// do nothing
}
pressLocation=null;
dragLocation=null;
}
public void mouseDragged(int mod, Point loc) {
if(pressLocation!=null) { // initial drag actions following mouse press
dragLocation=pressLocation; // consider dragging to be from start point
if(Math.abs(loc.x-pressLocation.x)<dragMinimum && Math.abs(loc.y-pressLocation.y)<dragMinimum) {
return; // not dragged far enough to count as drag (yet)
}
// action drag from press location
pressLocation=null;
}
else {
// action drag from last drag location
dragLocation=copyLocation(loc,dragLocation);
}
}
And note, I also had problems with Java some JVM's generating click events after dragging, which I had to detect and suppress.
If I read your question correctly, you're tracking both click and mousedrag events. Can you track the coordinates upon mousedown, followed by a short computation in mousedrag to see if the mouse has moved your desired minimum numbers of pixels? Of course, you then also want to cancel/reset on mouseup or when the mouse is dragged outside the bounds of your JComponent.
Caveat: I haven't done this myself, but I think it's where I'd start if it were me.
Software Monkey's code seemed to be missing some code, so I wrote this solution:
navigationTree.addMouseListener(new DragInsensitiveMouseClickListener(10) {
#Override
public void mouseClicked(MouseEvent e) {
TreePath treePath = navigationTree.getPathForLocation(e.getX(), e.getY());
if(treePath != null) {
processChoice();
}
}
});
This will still fire the mouseClicked() event when the user produces at most 10 pixels of "drag travel".
The code for the click listener:
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class DragInsensitiveMouseClickListener extends MouseAdapter {
private final int allowedTravel;
public Point mouseDownPoint;
public DragInsensitiveMouseClickListener(int allowedTravel) {
this.allowedTravel = allowedTravel;
}
#Override
public void mousePressed(MouseEvent e) {
mouseDownPoint = e.getPoint();
}
#Override
public void mouseReleased(MouseEvent e) {
double horizontalTravel = Math.abs(mouseDownPoint.getX() - e.getX());
double verticalTravel = Math.abs(mouseDownPoint.getY() - e.getY());
if (horizontalTravel < allowedTravel && verticalTravel < allowedTravel) {
mouseClicked(e);
}
}
}

Categories

Resources