File "ShapeMoving.java"
Full Path: /home/analogde/www/Ebook/Informatique/JAVA/Code/ShapeMoving.java
File size: 1.78 KB
MIME-type: text/x-c
Charset: utf-8
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ShapeMoving extends JFrame {
ShapeMoving() {
super("Shape Moving Demo");
setSize(600, 600);
add(new DrawingPanel());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private class DrawingPanel extends JPanel implements MouseMotionListener {
private final int size = 100;
private Rectangle shape = null;
DrawingPanel() {
addMouseMotionListener(this);
addMouseListener(new MouseAdapter(){
@Override
public void mousePressed(MouseEvent me) {
int x = me.getX();
int y = me.getY();
if(!selectedExistingRectangle(x, y)) {
setRectangle(x, y);
}
}
});
}
@Override
public void mouseDragged(MouseEvent me) {
int x = me.getX();
int y = me.getY();
if(selectedExistingRectangle(x, y)) {
setRectangle(x, y);
}
}
@Override
public void mouseMoved(MouseEvent me) {}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if(shape == null) return;
((Graphics2D)g).fill(shape);
}
boolean selectedExistingRectangle(int x, int y) {
return shape != null && shape.contains(x, y);
}
void setRectangle(int x, int y) {
shape = new Rectangle(x-(size/2), y-(size/2), size, size);
repaint();
}
}
public static void main(String[] args) {
new ShapeMoving();
}
}