page précédantetable des matièrespage suivante

Canevas et Dessin

    Pour pouvoir dessiner en Java on a besoin d'un objet de la classe "Canvas" (membre du paquetage "awt") . Les applications doivent le créer explicitement.
 
Pour les applets un objet "Canvas" est créé automatiquement dont les dimensions sont déterminés par les parametres "hight" et "width" de l'applet. Tous ce qu'on dessine en dehors du canevas n'est pas visible.

Les coordonnées cartésiennes du canevas sont calculées selont la figure
 

Les utilitaires pour dessiner des formes diverses se trouvent dans la classe "Graphics" .
 
 
          clearRect()
          copyArea()
          drawArc()
          drawLine()
          drawOval()
          drawPolygon()
          drawRect()
          drawRoundRect()
          drawString()
          fillArc()
          fillOval()
          fillPolygon()
          fillRect()
          fillRoundRect()
          getColor()
          getFont()
          getFontMetrics()
          setColor()
          setFont()

 La fonction qui doit faire les dessins est nommée "paint()":

    public void paint(Graphics g) {...}

elle a un paramètre - objet de la classe "Graphics" qu'on doit utiliser pour dessiner quoi que soit sur le canevas. Pour les applets la méthode "paint()" est appelée par le "browser" une fois - après les méthodes "init()" et "start()".Si on veut créer un dessin il faut redéfinir la méthode "paint()".

Par exemple

    public void paint(Graphics g) {
            g.drawLine(5, 10, 23, 10);
   }

Dessine une ligne droite -début aux coordonnées 5,10 et fin - aux coordonnées 23,10.

g represente le paramètre de la fonction "paint()".
 

Exemple - dessin d'un rectangle avec des angles arrondis

 
import java.awt.*;
import java.applet.*;
public class RectangleArrondi extends Applet {
    public void paint (Graphics g){
          g.fillRoundRect(50, 30, 95, 170, 15, 15);
               // paramètres: x,y,width, height,arcWidth,arcHeight
    }
}

 

Deuxième exemple

import java.applet.Applet;
import java.awt.*;

public class Ball extends Applet{
    int x,y,l, h;
    Color c;
    public void init(){
        x=y=100;
        l=h=50;
    }
    public void paint(Graphics g){
        g.setColor(Color.red);
        g.fillOval(x, y, l, h);
    }
}

Exemple suivant

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class Pgn0 extends Applet{
    int pointNum=0;
    int x[]= new int[0], y[]=new int[0],idx=0,yp=20;
    Label lx,ly;
    TextField tx, ty;
    X xls = new X();
    Y yls = new Y();
    public void init(){
        lx=new Label("x "+pointNum);
        tx=new TextField("",5);
        ly=new Label("y "+pointNum);
        ty=new TextField("",5);
        tx.addActionListener(xls);
        ty.setEditable(false);
        add(lx); add(tx);    add(ly); add(ty); 
    }
    public void paint(Graphics g){
        g.drawPolygon(x, y, pointNum);
        for(int i= 0;i<x.length;i++){
            g.drawString("["+x[i]+","+y[i]+"]", x[i], y[i]);
        }
    }
    class X implements ActionListener{
        public void actionPerformed(ActionEvent e){
            tx.setEditable(false);
            tx.removeActionListener(xls);
            ty.setEditable(true);
            ty.addActionListener(yls);      
        }
    }
    class Y implements ActionListener{
        public void actionPerformed(ActionEvent e){
            ty.setEditable(false);
            ty.removeActionListener(yls);
            tx.setEditable(true);
            tx.addActionListener(xls);
            addPt();
            repaint();
        }
    }
    void addPt(){
        pointNum++;
        int help[] = new int[pointNum];
        System.arraycopy(x, 0, help, 0, pointNum-1);
        x=help; x[pointNum-1]= Integer.parseInt(tx.getText());
        help = new int[pointNum];
        System.arraycopy(y, 0, help, 0, pointNum-1);
        y=help; y[pointNum-1]= Integer.parseInt(ty.getText());
        lx.setText("x"+pointNum);
        ly.setText("y"+pointNum);
     
    }
}

C'est possible d'utiliser la souris pour introduction des points

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class Pgn extends Applet{
    int pointNum=0;
    int x[]= new int[0], y[]=new int[0],idx=0,yp=20;   
    MouseHandler mh = new MouseHandler();
    public void init(){
        addMouseListener(mh);
        add(new Label("Click mouse to introduce a point"));
    }
    public void paint(Graphics g){
        g.drawPolygon(x, y, pointNum);
        for(int i= 0;i<x.length;i++){
            g.drawString("["+x[i]+","+y[i]+"]", x[i], y[i]);
        }
    }
    class MouseHandler extends MouseAdapter {
        public void mousePressed(MouseEvent e){
           int xm=e.getX();
           int ym=e.getY();
           addPt(xm,ym);
           repaint();
           validate();
         }
     }  
    void addPt(int xm, int ym){
        pointNum++;
        int help[] = new int[pointNum];
        System.arraycopy(x, 0, help, 0, pointNum-1);
        x=help; x[pointNum-1]= xm;
        help = new int[pointNum];
        System.arraycopy(y, 0, help, 0, pointNum-1);
        y=help; y[pointNum-1]= ym;     
    }
}


Un exemple plus detaillé


import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.Math;
import java.util.Vector;

public class Draw extends Applet {
   Button lineButton = new Button("Line");
   Button ovalButton = new Button("Oval");
   Button rectButton = new Button("Rectangle");
   Button clearButton = new Button("Clear");
   MyCanvas canvas = new MyCanvas(TwoPointObject.LINE);
   int screenWidth = 400;
   int screenHeight = 400;
   public void init() {
      setBackground(Color.green);
      setLayout(new BorderLayout());
      add("Center",canvas);
      setupButtons();
      resize(screenWidth,screenHeight);
   }
   void setupButtons() {
      lineButton.addActionListener(new ButtonHandler());
      ovalButton.addActionListener(new ButtonHandler());
      rectButton.addActionListener(new ButtonHandler());
      clearButton.addActionListener(new ButtonHandler());
      Panel panel = new Panel();
      panel.add(lineButton);
      panel.add(ovalButton);
      panel.add(rectButton);
      panel.add(clearButton);
      add("North",panel);
   }
   class ButtonHandler implements ActionListener {
      public void actionPerformed(ActionEvent ev){
         String s=ev.getActionCommand();
         if(s.equals("Clear")) canvas.clear();
         else if(s.equals("Line"))
             canvas.setTool(TwoPointObject.LINE);
         else if(s.equals("Oval"))
             canvas.setTool(TwoPointObject.OVAL);
         else if(s.equals("Rectangle"))
             canvas.setTool(TwoPointObject.RECTANGLE);
      }
   }
}
class MyCanvas extends Canvas {
   int tool = TwoPointObject.LINE;
   Vector objects = new Vector();
   TwoPointObject current;
   boolean newObject = false;
   public MyCanvas(int toolType) {
         super();
         tool = toolType;
         addMouseListener(new MouseHandler());
         addMouseMotionListener(new MouseMotionHandler());
   }
   public void setTool(int toolType) {
       tool = toolType;
   }
   public void clear() {
        objects.removeAllElements();
        repaint();
   }
   public void paint(Graphics g) {
        int numObjects = objects.size();
        for(int i=0;i<numObjects;++i) {
              TwoPointObject obj = (TwoPointObject) objects.elementAt(i);
              obj.draw(g);
        }
        if(newObject) current.draw(g);
   }
   class MouseHandler extends MouseAdapter {
         public void mousePressed(MouseEvent e){
              current = new TwoPointObject(tool,e.getX(),e.getY());
              newObject = true;
         }
         public void mouseReleased(MouseEvent e){
              if(newObject) {
                   objects.addElement(current);
                   newObject = false;
              }
         }
   }

   class MouseMotionHandler extends MouseMotionAdapter {
        public void mouseDragged(MouseEvent e){
              int x = e.getX();
              int y = e.getY();
              if(newObject) {
                      int oldX = current.endX;
                      int oldY = current.endY;
                      if(tool != TwoPointObject.LINE) {
                               if(x > current.startX) current.endX = x;
                               if(y > current.startY) current.endY = y;
                               int width = Math.max(oldX,current.endX) - current.startX + 1;
                               int height = Math.max(oldY,current.endY) - current.startY + 1;
                               repaint(current.startX,current.startY,width,height);
                      }else{
                             current.endX = x;
                             current.endY = y;
                             int startX = Math.min(Math.min(current.startX,current.endX),oldX);
                             int startY = Math.min(Math.min(current.startY,current.endY),oldY);
                             int endX = Math.max(Math.max(current.startX,current.endX),oldX);
                             int endY = Math.max(Math.max(current.startY,current.endY),oldY);
                             repaint(startX,startY,endX-startX+1,endY-startY+1);
                       }
               }
          }
     }
}
class TwoPointObject {
    public static int LINE = 0;
    public static int OVAL = 1;
    public static int RECTANGLE = 2;
    public int type, startX, startY, endX, endY;
    public TwoPointObject(int objectType,int x1,int y1,int x2,int y2) {
            type = objectType;
            startX = x1;
            startY = y1;
            endX = x2;
            endY = y2;
    }
    public TwoPointObject(int objectType,int x,int y) {
            this(objectType,x,y,x,y);
    }
    public TwoPointObject() {
            this(LINE,0,0,0,0);
    }
    public void draw(Graphics g) {
            if(type == LINE) g.drawLine(startX,startY,endX,endY);
            else{
                   int w = Math.abs(endX - startX);
                   int l = Math.abs(endY - startY);
                   if(type == OVAL) g.drawOval(startX,startY,w,l);
                   else g.drawRect(startX,startY,w,l);
             }
    }
}