package dnd;
/*
* LabelVerschiebenDemo.java
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class LabelVerschiebenDemo extends JFrame {
private JLabel jLabel1, jLabel2, hitLabel;
private JPanel mainPanel;
private int y1, x1, deltaY, deltaX;
public LabelVerschiebenDemo() {
super("Label Verschieben Demo");
setSize(400,300);
setLocationRelativeTo(null);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//JComponents erzeugen:
mainPanel = new JPanel();
jLabel1 = new JLabel("jLabel1");
jLabel2 = new JLabel("jLabel2");
//Layout:
mainPanel.setLayout(null);
mainPanel.add(jLabel1);
jLabel1.setBounds(140, 90, 80, 14);
mainPanel.add(jLabel2);
jLabel2.setBounds(140, 150, 80, 14);
getContentPane().add(mainPanel, BorderLayout.CENTER);
//Listeners:
mainPanel.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(final MouseEvent evt) {
mainPanelMouseDragged(evt);
}
});
mainPanel.addMouseListener(new MouseAdapter() {
public void mousePressed(final MouseEvent evt) {
mainPanelMousePressed(evt);
}
public void mouseReleased(final MouseEvent evt) {
mainPanelMouseReleased(evt);
}
});
}
private void mainPanelMousePressed(final MouseEvent evt) {
Component c = mainPanel.getComponentAt(evt.getPoint());
if (c instanceof JLabel) {
hitLabel = (JLabel) c;
hitLabel.setBorder(new BevelBorder(BevelBorder.RAISED));
deltaX = evt.getX() - hitLabel.getX();
deltaY = evt.getY() - hitLabel.getY();
}
}
private void mainPanelMouseDragged(final MouseEvent evt) {
if (hitLabel != null) {
int x = evt.getX() - deltaX;
int y = evt.getY() - deltaY;
hitLabel.setLocation(x, y);
mainPanel.setComponentZOrder(hitLabel, 0);// JDK 1.5
mainPanel.repaint();
}
}
private void mainPanelMouseReleased(final MouseEvent evt) {
if( hitLabel != null ){
hitLabel.setBorder(null);
mainPanel.repaint();
hitLabel = null;
}
}
public static void main(final String args[]) {new LabelVerschiebenDemo().setVisible(true);}
}