package demo;
/*
* MovingPictures.java
*/
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
public class MovingPictures extends JFrame {
public MovingPictures() {
super("MovingPictures");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(400, 300);
setLocationRelativeTo(null);
PictureContainer cont = new PictureContainer();
Image img = loadImage();
cont.add(new Picture(50, 50, img));
cont.add(new Picture(200, 70, img));
add(cont);
}
private Image loadImage() {
Image img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
Graphics g = img.getGraphics();
g.setColor(Color.GREEN);
g.fillRect(0, 0, 100, 100);
g.setColor(Color.RED);
g.fillOval(20, 20, 20, 30);
g.fillOval(60, 20, 20, 30);
g.fillOval(40, 60, 20, 30);
return img;
}
public static void main(final String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MovingPictures().setVisible(true);
}
});
}
}
/*
* PictureContainer
*/
class PictureContainer extends JPanel implements MouseListener, MouseMotionListener {
private Picture hitPicture;
private double deltaX;
private double deltaY;
public PictureContainer() {
setLayout(null);
addMouseListener(this);
addMouseMotionListener(this);
}
public void mousePressed(final MouseEvent e) {
Component c = getComponentAt(e.getPoint());
hitPicture = null;
if (c instanceof Picture) {
hitPicture = (Picture) c;
deltaX = e.getX() - hitPicture.getX();
deltaY = e.getY() - hitPicture.getY();
}
}
public void mouseDragged(final MouseEvent e) {
if (hitPicture != null) {
int x = (int) (e.getX() - deltaX);
int y = (int) (e.getY() - deltaY);
hitPicture.setLocation(x, y);
}
}
public void mouseClicked(final MouseEvent e) {
}
public void mouseReleased(final MouseEvent e) {
}
public void mouseEntered(final MouseEvent e) {
}
public void mouseExited(final MouseEvent e) {
}
public void mouseMoved(final MouseEvent e) {
}
}
/*
* Picture
*/
class Picture extends JLabel {
public Picture(final int x, final int y, final Image img) {
setBounds(x, y, img.getWidth(this), img.getHeight(this));
setIcon(new ImageIcon(img));
}
}