1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Vector;
@SuppressWarnings("serial")
public class DrawRectangleOnMouseClick extends JPanel{
MouseHandler mouseHandler = new MouseHandler();
ArrayList<Point> arrCoord = new ArrayList<Point>();
Point tempPoint = new Point (0,0);
public int cptCoord;
boolean drawing;
int recupX,recupY,recupFY,recupFX;
public DrawRectangleOnMouseClick(){
this.setPreferredSize(new Dimension(500, 400));
this.addMouseListener(mouseHandler);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i=0; i < arrCoord.size();i+=2) {
recupX = arrCoord.get(i).x;
recupY = arrCoord.get(i).y;
recupFX = arrCoord.get(i+1).x;
recupFY = arrCoord.get(i+1).y;
System.out.println("Hello, Earthling" + recupX);
g.drawRect(recupX,recupY,recupFX,recupFY);
}
System.out.println("Coord de 1X : " + arrCoord.size());
}
private class MouseHandler extends MouseAdapter {
public void mousePressed(MouseEvent e) {
drawing = true;
tempPoint.x = e.getX();
tempPoint.y = e.getY();
arrCoord.add(tempPoint);
}
public void mouseReleased(MouseEvent e) {
drawing = false;
tempPoint.x = e.getX();
tempPoint.y = e.getY();
arrCoord.add(tempPoint);
repaint();
}
}
public static void main(String[] args) {
JFrame f = new JFrame("Draw Rectangle On Mouse Click");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new DrawRectangleOnMouseClick());
f.pack();
f.setVisible(true);
}
} |
Partager