Restricting dragging a JB
To: comp.lang.java.gui
Hello,
The following code creates a JPanel on which JButtons can be added by
clicking JButton. Also. these created JButtons can be dragged around
in the JPanel.
<code>
import java.awt.*;
import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class DragTest extends JFrame {
private JPanel dragArea;
private JButton jButton1;
public DragTest() {
GridBagConstraints gridBagConstraints;
dragArea = new JPanel();
jButton1 = new JButton();
dragArea.setBorder(new LineBorder(Color.BLACK, 2));
getContentPane().setLayout(new GridBagLayout());
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
GroupLayout dragAreaLayout = new GroupLayout(dragArea);
dragArea.setLayout(dragAreaLayout);
dragAreaLayout.setHorizontalGroup(
dragAreaLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0,
376, Short.MAX_VALUE)
);
dragAreaLayout.setVerticalGroup(
dragAreaLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0,
217, Short.MAX_VALUE)
);
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.anchor = GridBagConstraints.NORTH;
getContentPane().add(dragArea, gridBagConstraints);
jButton1.setText("Click Me");
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = GridBagConstraints.SOUTH;
getContentPane().add(jButton1, gridBagConstraints);
pack();
}
private void jButton1ActionPerformed(ActionEvent evt)
{
JButton jButton = new JButton("Drag Me");
jButton.setBounds(50,50,100,50);
jButton.addMouseMotionListener(new DragHandler());
dragArea.add(jButton);
dragArea.repaint();
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new DragTest().setVisible(true);
}
});
}
/* Inner class to handle dragging of items on the workspace */
class DragHandler extends MouseMotionAdapter{
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>
The problem here is that the JButtons added to the JPanel can be
dragged out side the JPanel. Kindly advice how to restrict dragging
of those JButton to be only inside the JPanel
Thanks in advance
Chanchal
---
* Synchronet * The Whitehouse BBS --- whitehouse.hulds.com --- check it out free usenet!
--- Synchronet 3.15a-Win32 NewsLink 1.92
Time Warp of the Future BBS - telnet://time.synchro.net:24