|
-
Mar 17th, 2002, 02:15 PM
#1
Moving a component...
Say I've got a JFrame with a null Layout. I'm trying to move a component in the JFrame when the mouseDragged event for the component is fired (Similar to how a Windows Listview works when you drag the column header). I just can't seem to get the arithmetic to position it.
So far, I've got...
Code:
Point mPMouseDown = new Point();
public void mousePressed(MouseEvent me)
{
isArmed = true;
mPMouseDown.setLocation((int)me.getX(),(int)me.getY());
this.repaint();
}
public void mouseDragged(MouseEvent me)
{
int t = (int)mPMouseDown.getY();
int l = (int)mPMouseDown.getX();
this.setLocation((int)this.getLocation().getX()+(l/2),(int)this.getLocation().getY());
}
The code in mouseDragged is completely awful, but I forget the code I had that worked better. What I'm basically looking for is, if the mouse is pressed say 4 pixels in to the component, when I drag, I want the left of the component to stay 4 pixels left of the mouse until I release it.
Laugh, and the world laughs with you. Cry, and you just water down your vodka.
Take credit, not responsibility
-
Mar 17th, 2002, 10:07 PM
#2
Dazed Member
Here's my stab at this problem. But the only problem is that when the mouse is dragged within the JButton the JButton goes nuts and runs away. Ill have to look at my code again tommorow.
Code:
public class DragDrop{
public static void main(String[] args){
boolean pressed = false;
JButton dragme = new JButton("Drag Me!");
dragme.addMouseMotionListener(new Dragged(dragme));
dragme.setSize(50,25);
JFrame dragdrop = new JFrame("DragDrop");
Container content = dragdrop.getContentPane();
content.setLayout(null);
content.add(dragme); // start xy at 0
dragdrop.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
dragdrop.setSize(400,300);
dragdrop.setVisible(true);
}
}
class Dragged extends MouseMotionAdapter{
JButton dragme;
public Dragged(JButton dragme){
this.dragme = dragme;
}
public void mouseDragged(MouseEvent e){
dragme.setLocation(e.getY(),e.getX());
}
}
-
Mar 17th, 2002, 10:28 PM
#3
Code:
public void mouseDragged(MouseEvent me)
{
me = SwingUtilities.convertMouseEvent(this,me,me.getComponent().getParent());
this.setLocation((int)(me.getX()-(this.getWidth()/2)),(int)this.getLocation().getY());
}
I came up with this a few minutes ago, it seems to work pretty well.
Laugh, and the world laughs with you. Cry, and you just water down your vodka.
Take credit, not responsibility
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|