Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I propose a simple, but well-working solution, found out by myself ;)</p> <p>What do I do?</p> <ul> <li>When mouse is pressed, I record the <strong>cursor's</strong> position <strong>on screen</strong>, and the <strong>component's</strong> position.</li> <li>When mouse is dragged, I calculate the <strong>difference</strong> between new and old <strong>cursor's</strong> position <strong>on screen</strong>, and move the component <strong>by this difference</strong>.</li> </ul> <p><em>Tested with latest JDK 6 unter Linux (OpenSuse, KDE3),<br> but hey, it's Java Swing, should work equally everywhere.</em></p> <p><strong>Here goes the code:</strong></p> <pre><code>import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; public class MyDraggableComponent extends JComponent { private volatile int screenX = 0; private volatile int screenY = 0; private volatile int myX = 0; private volatile int myY = 0; public MyDraggableComponent() { setBorder(new LineBorder(Color.BLUE, 3)); setBackground(Color.WHITE); setBounds(0, 0, 100, 100); setOpaque(false); addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { screenX = e.getXOnScreen(); screenY = e.getYOnScreen(); myX = getX(); myY = getY(); } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }); addMouseMotionListener(new MouseMotionListener() { @Override public void mouseDragged(MouseEvent e) { int deltaX = e.getXOnScreen() - screenX; int deltaY = e.getYOnScreen() - screenY; setLocation(myX + deltaX, myY + deltaY); } @Override public void mouseMoved(MouseEvent e) { } }); } } public class Main { public static void main(String[] args) { JFrame f = new JFrame("Swing Hello World"); // by doing this, we prevent Swing from resizing // our nice component f.setLayout(null); MyDraggableComponent mc = new MyDraggableComponent(); f.add(mc); f.setSize(500, 500); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); f.setVisible(true); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload