/**
*
*/
package de.tutorials;
import java.awt.Cursor;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
/**
* @author Thomas
*
*/
public class MoveableIconExample extends JFrame {
static int width = 400, height = 300;
boolean shouldIconMove;
BufferStrategy strategy;
BufferedImage image;
int imageWidth;
int imageHeight;
Rectangle rectangle = new Rectangle(200, 150);
Point p;
Cursor normalCursor, imageMoveCursor;
Thread runner = new Thread() {
public void run() {
try {
image = ImageIO.read(new File("c:/sample.gif"));
imageWidth = image.getWidth();
imageHeight = image.getHeight();
int xPos = 200;
int yPos = 150;
rectangle.setLocation(100, 75);
while (true) {
Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
g.clearRect(0, 0, width, height);
if (shouldIconMove && rectangle.contains(p)) {
xPos = p.x - imageWidth / 2;
yPos = p.y - imageHeight / 2;
}
g.drawRect(rectangle.x, rectangle.y, rectangle.width,
rectangle.height);
g.drawImage(image, xPos, yPos, null);
g.dispose();
strategy.show();
TimeUnit.MILLISECONDS.sleep(20L);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
public MoveableIconExample() {
super("MoveableIconExample");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
setSize(width, height);
setVisible(true);
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
p = e.getPoint();
if (rectangle.contains(p) && shouldIconMove) {
setCursor(imageMoveCursor);
} else {
setCursor(normalCursor);
}
}
});
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
Point clickedPoint = e.getPoint();
if (Math.abs(p.x - clickedPoint.x) <= imageWidth
&& Math.abs(p.y - clickedPoint.y) <= imageHeight
&& !shouldIconMove && rectangle.contains(clickedPoint)) {
shouldIconMove = true;
} else {
shouldIconMove = false;
}
}
});
normalCursor = getCursor();
imageMoveCursor = Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR);
createBufferStrategy(2);
strategy = getBufferStrategy();
runner.start();
}
/**
* @param args
*/
public static void main(String[] args) {
new MoveableIconExample();
}
}