Originariamente inviato da claujava
ad esempio supponiamo di voler rendere mobile un JButton
codice:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DragComponentTestFrame extends JFrame {
public DragComponentTestFrame() {
super("Test drag di componenti");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(400, 300);
Container contentPane = getContentPane();
contentPane.setLayout(null); // Nessun layout manager
JButton b = new JButton("JButton");
b.setBounds(40, 50, 90, 40);
ComponentDragHandler.register(b);
JLabel l = new JLabel("JLabel");
l.setOpaque(true);
l.setBackground(Color.LIGHT_GRAY);
l.setHorizontalAlignment(SwingConstants.CENTER);
l.setBounds(190, 120, 80, 30);
ComponentDragHandler.register(l);
contentPane.add(b);
contentPane.add(l);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new DragComponentTestFrame().setVisible(true);
}
});
}
}
class ComponentDragHandler extends MouseAdapter implements MouseMotionListener {
private int baseX;
private int baseY;
public void mousePressed(MouseEvent e) {
baseX = e.getX();
baseY = e.getY();
}
public void mouseDragged(MouseEvent e) {
Component comp = e.getComponent();
Point compPoint = comp.getLocation();
Point clickPoint = e.getPoint();
int x = compPoint.x + clickPoint.x - baseX;
int y = compPoint.y + clickPoint.y - baseY;
comp.setLocation(x, y);
}
public void mouseMoved(MouseEvent e) {}
public static void register(Component c) {
ComponentDragHandler handler = new ComponentDragHandler();
c.addMouseListener(handler);
c.addMouseMotionListener(handler);
}
}