Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This modified example is based on MadProgrammer's code.</p> <p>It shows the behavior I described in my original post. Thank you all for your valuable help, especially MadProgrammer and Coupon22. Try it out.</p> <pre><code>import java.awt.*; import javax.swing.*; import java.awt.event.MouseEvent; import java.awt.event.MouseAdapter; public class TestMouseDrag { public static void main(String[] args) { new TestMouseDrag(); } public TestMouseDrag() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException ex) { } catch (InstantiationException ex) { } catch (IllegalAccessException ex) { } catch (UnsupportedLookAndFeelException ex) { } JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); frame.add(new DragMyIcon("C://image.jpg")); frame.pack(); frame.setSize(500,500); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } protected class DragMyIcon extends JPanel { public static final long serialVersionUID = 172L; private JLabel label; public DragMyIcon(String path) { setLayout(null); ImageIcon icon = null; icon = new ImageIcon(path); label = new JLabel(icon); label.setBounds(0,0,icon.getIconWidth(), icon.getIconHeight()); setBounds(0,0,icon.getIconWidth(), icon.getIconHeight()); label.setHorizontalAlignment(JLabel.CENTER); label.setVerticalAlignment(JLabel.CENTER); add(label); MouseHandler handler = new MouseHandler(); label.addMouseListener(handler); label.addMouseMotionListener(handler); } } protected class MouseHandler extends MouseAdapter { private boolean active = false; private int xDisp; private int yDisp; @Override public void mousePressed(MouseEvent e) { active = true; JLabel label = (JLabel) e.getComponent(); xDisp = e.getPoint().x - label.getLocation().x; yDisp = e.getPoint().y - label.getLocation().y; label.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); } @Override public void mouseReleased(MouseEvent e) { active = false; JLabel label = (JLabel) e.getComponent(); label.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } @Override public void mouseDragged(MouseEvent e) { if (active) { JLabel label = (JLabel) e.getComponent(); Point point = e.getPoint(); label.setLocation(point.x - xDisp, point.y - yDisp); label.invalidate(); label.repaint(); } } @Override public void mouseMoved(MouseEvent e) { } } </code></pre> <p>}</p>
 

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