Hi,
I have a JPanel into which JButtons are added. These JButtons can be
dragged around in the JPanel. I need to restrict the dragging so that
the JButton cannot be dragged outside the JPanel.
Here is my code
<code>
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DragTest extends JFrame {
private JButton jButton1;
private JPanel jPanel1;
public DragTest() {
jPanel1 = new JPanel();
jButton1 = new JButton();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jPanel1.setLayout(null);
jPanel1.setBackground(new Color(255, 255, 255));
jButton1.setText("jButton1");
jPanel1.add(jButton1);
jButton1.setBounds(170, 160, 75, 23);
jButton1.addMouseMotionListener(new DragHandler(this));
getContentPane().add(jPanel1, BorderLayout.CENTER);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width-400)/2, (screenSize.height-300)/2,
400, 300);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new DragTest().setVisible(true);
}
});
}
class DragHandler extends MouseMotionAdapter{
DragTest frame;
DragHandler(DragTest frame){
this.frame = frame;
}
public void mouseDragged(MouseEvent e) {
Component c = e.getComponent();
c.setLocation(c.getX() + e.getX()-c.getWidth()/2, c.getY()
+ e.getY()-c.getHeight()/2);
}
}
}
</code>
Kindly advice how i can restrict the dragging
Thanks in advance
Chanchal
Alexander.V.Kasatkin@gmail.com - 04 Jan 2008 15:38 GMT
> Kindly advice how i can restrict the dragging
You may check an intersection of the parent rectangle and new
component one:
<code>
class DragHandler extends MouseAdapter {
private int diffX;
private int diffY;
DragHandler() {
}
public void register(Component c)
{
c.addMouseListener(this);
c.addMouseMotionListener(this);
}
public void unregister(Component c)
{
c.removeMouseListener(this);
c.removeMouseMotionListener(this);
}
public void mousePressed(MouseEvent e) {
diffX = e.getX();
diffY = e.getY();
}
public void mouseDragged(MouseEvent e) {
final Component c = e.getComponent();
final Container p = c.getParent();
final int x = c.getX() + e.getX() - diffX;
final int y = c.getY() + e.getY() - diffY;
Rectangle cr = new Rectangle(x, y, c.getWidth(),
c.getHeight());
Rectangle cp = new Rectangle(0, 0, p.getWidth(),
p.getHeight());
if (cp.intersects(cr))
{
c.setLocation(x, y);
}
}
}
</code>
BR, Alex