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.
Related
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
}
}
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.
I have to draw a Line in Java. I click one point, then release the mouse key, move the mouse (the end of the line should be where the mouse cursor is (a dynamic preview)) then click the mouse key again to make the line.
I see various questions on here, but most deal with holding a mouse button and dragging the mouse.
My question is, how can I draw a line dynamically using the method above. I am concerned about repainting. I had code earlier and it drew all the lines as I moved the mouse. Is there a way to just have a preview.
You need need to create a application implementing both a MouseEventListener and a MouseMotionListener. Use the MouseEventListener method mouseClicked to check whether the mouse has been clicked and subsequently the MouseMotionListener method MouseMoved to update the other end of the line to your mouse's position. Finally you use the MouseEventListener again to pinpoint the end location of the line.
I hope this helps.
Take a look at:
http://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html and http://docs.oracle.com/javase/tutorial/uiswing/events/mousemotionlistener.html.
There's a lot of information missing in your post, so it will be difficult to offer an exact solution, but here is the general idea. Assuming that you need a transparent JComponent that receive mouse events and paint your line preview, the code would look something like this.
public class MyLinePreviewComponent extends JComponent {
Point sourcePoint;
Point destinationPoint;
pubic MyLinePreviewComponent() {
this.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (sourcePoint == null)
sourcePoint = e.getPoint();
else
sourcePoint = null;
repaint();
}
});
this.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
if (sourcePoint != null)
targetPoint = e.getPoint();
repaint();
}
});
}
public void paintComponent(Graphics g) {
if (sourcePoint != null && destinationPoint != null) {
g.setColor(Color.red);
g.drawLine(sourcePoint.x, sourcePoint.y, destinationPoint.x, destinationPoint.y);
}
}
}
Note that I did not run this code.
If the line preview feature has to be added to an existing component, then you will have to repaint the regular content in paintComponent() before paiting the line.
I have a vector (_storedShapes) to store the painted rectangles (_rect). I also plan on adding ellipses. What I am trying to do is add a shape to the spot on the screen that I click and be able to resize it. Here is a website with a demo of what I am trying to do http://code.google.com/p/tangram-canvas/downloads/detail?name=TangramCanvas-1.2.zip.
The only difference from this demo is that I want my shape to expand on all sides from its center as I drag it.
From my code right now, a pre-sized rectangle pops up on the canvas where I click and then when I drag, just follows the cursor on the screen.
private class DrawSListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
_preX = (int) (_rect.getX() - e.getX());
_preY = (int) (_rect.getY() - e.getY());
DrawingPanel dp = new DrawingPanel();
_rect = new SketchyRectangle(dp);
System.out.println("new rec");
// if (_rect.contains(e.getPoint())) {
_rect.setLocation(e.getX(), e.getY());
System.out.println("setLocation");
repaint();
System.out.println("paint");
//}
}
}
/**
* Private class DrawListener is called when the DrawEllipse or DrawRectangle radio buttons are selected.
*
*/
private class DrawListener implements MouseMotionListener {
public void mouseDragged(MouseEvent e) {
if (_rect.contains(e.getPoint())) {
_rect.setLocation(_preX, _preY);
_storedShapes.add(_rect);
repaint();
}
}
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
}
I would keep two coordinates in the object (or wherever makes sense): prevDragCoord, shapeCenter. On mouse click store the coordinate of the event in both members. On mouse drag, update the rectangle size by adding to it the difference of the current event coordinate minus the coordinate stored in the object. Set the rectangle's location by setting the difference between the shapeCenter member and the rectangle size divided by 2 (e.g. shapeCenter.x - rect.xLength/2). Store the current coordinate in the object's coordinate member so it's ready to update on any subsequent calls to your handler.
I'll leave the implementation up to you. Maybe you can do it with only one variable, or maybe no variables because the event object has some sort of awesome data in it to get this done. This should be the general idea anyway.
I've got a problem when trying to drag a JPanel. If I implement it purely in MouseDragged as:
public void mouseDragged(MouseEvent me) {
me.getSource().setLocation(me.getX(), me.getY());
}
I get a weird effect of the moved object bouncing between two positions all the time (generating more "dragged" events). If I do it in the way described in this post, but with:
public void mouseDragged(MouseEvent me) {
if (draggedElement == null)
return;
me.translatePoint(this.draggedXAdjust, this.draggedYAdjust);
draggedElement.setLocation(me.getX(), me.getY());
}
I get an effect of the element bouncing a lot less, but it's still visible and the element moves only ½ of the way the mouse pointer does. Why does this happen / how can I fix this situation?
OK. Old question but if anyone comes across this like I did this can be solved relatively simply. For dragging a JPanel in a JFrame I did:
#Override
public void mousePressed(MouseEvent e) {
if (panel.contains(e.getPoint())) {
dX = e.getLocationOnScreen().x - panel.getX();
dY = e.getLocationOnScreen().y - panel.getY();
panel.setDraggable(true);
}
}
#Override
public void mouseDragged(MouseEvent e) {
if (panel.isDraggable()) {
panel.setLocation(e.getLocationOnScreen().x - dX, e.getLocationOnScreen().y - dY);
dX = e.getLocationOnScreen().x - panel.getX();
dY = e.getLocationOnScreen().y - panel.getY();
}
}
The key is to use .getLocationOnScreen() and update the adjustment at the end of each call of mouseDragged.
Try this
final Component t = e.getComponent();
e.translatePoint(getLocation().x + t.getLocation().x - px, getLocation().y + t.getLocation().y - py);
and add this method:
#Override
public void mousePressed(final MouseEvent e) {
e.translatePoint(e.getComponent().getLocation().x, e.getComponent().getLocation().y);
px = e.getX();
py = e.getY();
}
I don't know if you can just do it using a mouseDragged event. In the past I use mousePressed to save the original point and mouse dragged to get the current point. In both cases I translate the points to the location on the screen. Then the difference between the two points is easily calculated and the location can be set appropriately.
My general purpose class for this is the Component Mover class.