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 68 69 70
| public class DrawPanel extends JPanel{
int toolsActive;
int x_click, y_click, x_current, y_current;
public DrawPanel(){
try{
jbInit();
}
catch (Exception ex){
ex.printStackTrace();
}
}
public void dessinerCrayon(){
toolsActive = 1;
repaint();
}
public void dessinerRectangle(){
toolsActive = 2;
repaint();
}
public void dessinerLigne(){
toolsActive = 3;
repaint();
}
public void paintComponent(Graphics g){
// Appel de la méthode paintComponent de la classe mère
super.paintComponent(g);
// Conversion en un contexte 2D
Graphics2D g2 = (Graphics2D)g;
switch (toolsActive){
case 1:
g2.drawLine(x_click, y_click, x_current, y_current);
x_click = x_current;
y_click = y_current;
break;
case 2:
g2.drawRect(x_click, y_click, Math.abs(x_current - x_click),
Math.abs(y_current - y_click));
break;
case 3:
g2.drawLine(x_click, y_click, x_current, y_current);
break;
}
}
private void jbInit() throws Exception{
this.setBackground(Color.WHITE);
this.addMouseListener(new DrawPanel_this_mouseAdapter(this));
this.addMouseMotionListener(new DrawPanel_this_mouseMotionAdapter(this));
}
//Ecouteur souris pressée
public void this_mousePressed(MouseEvent e){
x_click = (int)e.getPoint().getX();
y_click = (int)e.getPoint().getY();
}
//Ecouteur souris déplacée
public void this_mouseDragged(MouseEvent e){
x_current = e.getX();
y_current = e.getY();
repaint();
} |
Partager