Dragging a Jlabel Around the Screen

Dragging a JLabel outside of a JFrame

Using JWindow test:

//http://stackoverflow.com/questions/4893265/dragging-a-jlabel-around-the-screen
private final JWindow window = new JWindow();
@Override
public void mouseDragged(MouseEvent me) {
if (dragLabel == null) {
return;
}
int x = me.getPoint().x - dragLabelWidthDiv2;
int y = me.getPoint().y - dragLabelHeightDiv2;
//dragLabel.setLocation(x, y);
window.add(dragLabel);
window.pack();
Point pt = new Point(x, y);
Component c = (Component)me.getSource();
SwingUtilities.convertPointToScreen(pt, c);
window.setLocation(pt);
window.setVisible(true);
repaint();
}
@Override public void mouseReleased(MouseEvent me) {
window.setVisible(false);
//...
}

Below is not tested code:
(may take some massaging to work, but this is the gist of it)

@Override public int getSourceActions(JComponent src) {
JLabel label = (JLabel)src;
window.add(label);
window.pack();
window.setVisible(true);
return MOVE;
}
//...
DragSource.getDefaultDragSource().addDragSourceMotionListener(new DragSourceMotionListener() {
@Override public void dragMouseMoved(DragSourceDragEvent dsde) {
Point pt = dsde.getLocation();
pt.translate(5, 5); // offset
window.setLocation(pt);
}
});

Drag and move a picture inside a JLabel with mouseclick

This is a basic example...

It works by dividing the label up into a 3x3 grid, where each cell represents a possible position for the icon.

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());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

protected class DragMyIcon extends JPanel {

private JLabel label;

public DragMyIcon() {

ImageIcon icon = null;

try {
icon = new ImageIcon(ImageIO.read(getClass().getResource("/bomb.png")));
} catch (IOException ex) {
ex.printStackTrace();
}

label = new JLabel(icon);
label.setHorizontalAlignment(JLabel.CENTER);
label.setVerticalAlignment(JLabel.CENTER);

setLayout(new BorderLayout());
add(label);

MouseHandler handler = new MouseHandler();
label.addMouseListener(handler);
label.addMouseMotionListener(handler);

}

}

protected class MouseHandler extends MouseAdapter {

private boolean active = false;

@Override
public void mousePressed(MouseEvent e) {

JLabel label = (JLabel) e.getComponent();
Point point = e.getPoint();

active = getIconCell(label).contains(point);
if (active) {
label.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
} else {
label.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_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();

int verticalAlign = label.getVerticalAlignment();
int horizontalAlign = label.getHorizontalAlignment();

if (isWithInColumn(label, point, 0)) {
horizontalAlign = JLabel.LEFT;
} else if (isWithInColumn(label, point, 1)) {
horizontalAlign = JLabel.CENTER;
} else if (isWithInColumn(label, point, 2)) {
horizontalAlign = JLabel.RIGHT;
}

if (isWithInRow(label, point, 0)) {
verticalAlign = JLabel.TOP;
} else if (isWithInRow(label, point, 1)) {
verticalAlign = JLabel.CENTER;
} else if (isWithInRow(label, point, 2)) {
verticalAlign = JLabel.BOTTOM;
}

label.setVerticalAlignment(verticalAlign);
label.setHorizontalAlignment(horizontalAlign);

label.invalidate();
label.repaint();

}
}

@Override
public void mouseMoved(MouseEvent e) {
}

protected boolean isWithInColumn(JLabel label, Point p, int gridx) {
int cellWidth = label.getWidth() / 3;
int cellHeight = label.getHeight();

Rectangle bounds = new Rectangle(gridx * cellWidth, 0, cellWidth, cellHeight);

return bounds.contains(p);
}

protected boolean isWithInRow(JLabel label, Point p, int gridY) {
int cellWidth = label.getWidth();
int cellHeight = label.getHeight() / 3;

Rectangle bounds = new Rectangle(0, cellHeight * gridY, cellWidth, cellHeight);

return bounds.contains(p);
}

private Rectangle getIconCell(JLabel label) {

Rectangle bounds = new Rectangle();

int cellWidth = label.getWidth() / 3;
int cellHeight = label.getHeight() / 3;

bounds.width = cellWidth;
bounds.height = cellHeight;

if (label.getHorizontalAlignment() == JLabel.LEFT) {
bounds.x = 0;
} else if (label.getHorizontalAlignment() == JLabel.CENTER) {
bounds.x = cellWidth;
} else if (label.getHorizontalAlignment() == JLabel.RIGHT) {
bounds.x = cellWidth * 2;
} else {
bounds.x = 0;
bounds.width = 0;
}
//if (label.getHorizontalAlignment() == JLabel.TOP) {
// bounds.y = 0;
//} else if (label.getHorizontalAlignment() == JLabel.CENTER) {
// bounds.y = cellHeight;
//} else if (label.getHorizontalAlignment() == JLabel.BOTTOM) {
// bounds.y = cellHeight * 2;
//} else {
// bounds.y = 0;
// bounds.height = 0;
//}
if (label.getVerticalAlignment() == JLabel.TOP) {
bounds.y = 0;
} else if (label.getVerticalAlignment() == JLabel.CENTER) {
bounds.y = cellHeight;
} else if (label.getVerticalAlignment() == JLabel.BOTTOM) {
bounds.y = cellHeight * 2;
} else {
bounds.y = 0;
bounds.height = 0;
}

return bounds;

}

}

}

UPDATED from feedback

This example basically uses a JLayerdPane to allow the repositioning of JLabels within it's container...

public class MoveMe {

public static void main(String[] args) {
new MoveMe();
}

public MoveMe() {
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 MoveMePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class MoveMePane extends JLayeredPane {

public MoveMePane() {
int width = 400;
int height = 400;
for (int index = 0; index < 10; index++) {
String text = "Label " + index;
JLabel label = new JLabel(text);
label.setSize(label.getPreferredSize());

int x = (int) Math.round(Math.random() * width);
int y = (int) Math.round(Math.random() * height);
if (x + label.getWidth() > width) {
x = width - label.getWidth();
}
if (y + label.getHeight() > width) {
y = width - label.getHeight();
}
label.setLocation(x, y);
add(label);
}

MoveMeMouseHandler handler = new MoveMeMouseHandler();
addMouseListener(handler);
addMouseMotionListener(handler);
}

@Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
}

public class MoveMeMouseHandler extends MouseAdapter {

private int xOffset;
private int yOffset;
private JLabel draggy;
private String oldText;

@Override
public void mouseReleased(MouseEvent me) {
if (draggy != null) {
draggy.setText(oldText);
draggy.setSize(draggy.getPreferredSize());
draggy = null;
}
}

public void mousePressed(MouseEvent me) {
JComponent comp = (JComponent) me.getComponent();
Component child = comp.findComponentAt(me.getPoint());
if (child instanceof JLabel) {
xOffset = me.getX() - child.getX();
yOffset = me.getY() - child.getY();

draggy = (JLabel) child;
oldText = draggy.getText();
draggy.setText("What a drag");
draggy.setSize(draggy.getPreferredSize());
}
}

public void mouseDragged(MouseEvent me) {
if (draggy != null) {
draggy.setLocation(me.getX() - xOffset, me.getY() - yOffset);
}
}
}
}

Java jLabel drag and drop from netbeans events context menu

As MadProgrammer pointed out, that was the issue. This is my mouse drag method:

private void jLabel2MouseDragged(java.awt.event.MouseEvent evt)  {                                     

Point p = SwingUtilities.convertPoint(evt.getComponent(), evt.getPoint(), getContentPane());
int x=p.x;
int y=p.y;

jLabel2.setLocation(x-120, y-120);
jLabel2.repaint();

}

The jLabel now moves smoothly.

My label is roughly 240x240 pixels, so I corrected the coordinates to have the center of the label placed where the mouse pointer is.

Thanks!

Moving a JLabel Around JPanel

Here is what I wanted:

public class LayerItem extends JLabel{

protected int lblYPt = 0;

public LayerItem(JPanel layers){
this.addMouseListener(new MouseAdapter(){
@Override
public void mousePressed(MouseEvent evt){
lblMousePressed(evt);
}
});

this.addMouseMotionListener(new MouseAdapter(){
@Override
public void mouseDragged(MouseEvent evt){
lblMouseDragged(evt);
}
});
}

public void lblMousePressed(MouseEvent evt){
lblYPt = evt.getY();
}

public void lblMouseDragged(MouseEvent evt){
Component parent = evt.getComponent().getParent();
Point mouse = parent.getMousePosition();
try{
if(mouse.y - lblYPt >= 30){
this.setBounds(0, mouse.y - lblYPt, 198, 50);
}
}catch(Exception e){
}
}
}


Related Topics



Leave a reply



Submit