IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

2D Java Discussion :

[Swing][Graphics2D] dessiner une flèche


Sujet :

2D Java

  1. #1
    Membre à l'essai
    Profil pro
    Inscrit en
    Avril 2004
    Messages
    28
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2004
    Messages : 28
    Points : 22
    Points
    22
    Par défaut [Swing][Graphics2D] dessiner une flèche
    Bonjour,
    Une petite question. Voilà je développe une appli qui permet de dessiner, anoter une image quelconque. J'arrive à dessiner tout ce que je veux (arc, carré, triangle, polygone. cercle. ligne...). Bref jusque là ca va.
    Par contre il faudrait que je puisse dessiner une flèche. Disons une ligne avec un triangle au bout
    Est-ce que quelqu'un sait comment faire. Car j'ai beau cherche c'est galère. J'ai déjà tenté de dessiner un triangle en lui applicant des transformation affine grâce à AffineTransform mais ca ne fonctionne pas très bien.
    Merci d'avance.

  2. #2
    Membre à l'essai
    Profil pro
    Inscrit en
    Avril 2004
    Messages
    28
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2004
    Messages : 28
    Points : 22
    Points
    22
    Par défaut
    Bon bein je me réponds à moi même.
    Il faut bien utiliser AffineTransforme avec le triangle. Cependat il faut bien décomposer les transformations.
    Voici le code évidemment imcomplet mais le plus important est là. Si quelqu'un a besoin de plus de détails qu'il me fasse signe.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
     
    	public void drawArrow(MouseEvent aEvent)
    	{
    		Graphics2D g2 = (Graphics2D)draggingPanel.getGraphics();
    		AffineTransform affineTransform = new AffineTransform();
    		Polygon triangle = new Polygon(new int[] {0,0,10},new int[] {-5,5,0},3);
    		Shape arrow;
    		double theta, alpha, beta;
    		theta = Math.atan((aEvent.getPoint().getY()-firstPoint.getY())/(aEvent.getPoint().getX()-firstPoint.getX()));
    		if(isDragging)
    		{
    			setParameters(g2);
    			drawingShape = new Line2D.Double(firstPoint.getX(), firstPoint.getY(), lastPoint.getX(), lastPoint.getY());
    			g2.setXORMode(Color.white);
    			g2.draw(drawingShape);
     
    			drawingShape = new Line2D.Double(firstPoint.getX(), firstPoint.getY(), aEvent.getPoint().getX(), aEvent.getPoint().getY());
    			g2.draw(drawingShape);
    			setLastPoint(aEvent);
    			g2.dispose();
    		}
    		else
    		{
    			graphicImage= backupImage.createGraphics();
    			setParameters(graphicImage);
    			theta = Math.atan((aEvent.getPoint().getY()-firstPoint.getY())/(aEvent.getPoint().getX()-firstPoint.getX()));
    			alpha = aEvent.getPoint().getX();
    			beta = aEvent.getPoint().getY();
    			affineTransform.setToRotation(theta);
    			arrow = affineTransform.createTransformedShape(triangle);
    			affineTransform.setToTranslation(alpha,beta);
    			drawingShape = new Line2D.Double(firstPoint.getX(), firstPoint.getY(), aEvent.getPoint().getX(), aEvent.getPoint().getY());
    			graphicImage.draw(drawingShape);
    			graphicImage.draw(affineTransform.createTransformedShape(arrow));
    			graphicImage.fill(affineTransform.createTransformedShape(arrow));
    			graphicImage.dispose();
    			g2.dispose();
    			repaint();
    		}
    	}

  3. #3
    Membre régulier Avatar de kaisse
    Profil pro
    Inscrit en
    Novembre 2003
    Messages
    100
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2003
    Messages : 100
    Points : 117
    Points
    117
    Par défaut
    Si tu veux, pour une appli que je suis en train de developper en ce moment, j'ai du implementer une methode de dessin de fleche. Bon il s'agit juste de fleches verticales vers le bas, mais ca doit etre facile a adapte.

    La methode prend en arggument la position haut gauche de la fleche, et la largeur et la hauteur du cadre dans lequel elle s'inscrit

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
     public static void drawArrow (Graphics g,
    				  int x,
    				  int y,
    				  int largeur,
    				  int hauteur)
        {
     
    	largeur = largeur / 3;
    	hauteur = hauteur / 3;
     
            g.fillRect (x + largeur, y,
    		    largeur, 2 * hauteur);
     
    	int abcisses[] = new int[] { x,
    				     x + (3 * largeur),
    				     x + (largeur * 3 / 2)};
    	int ordonnes[] = new int[] { y + (2 * hauteur),
    				     y + (2 * hauteur),
    				     y + (3 * hauteur)};
     
    	g.fillPolygon (abcisses, ordonnes, 3);
     
    	return;
        }
    }
    Tu n'as plus qu'a adapte avec un MouseListener je pense

  4. #4
    Membre à l'essai
    Profil pro
    Inscrit en
    Avril 2004
    Messages
    28
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2004
    Messages : 28
    Points : 22
    Points
    22
    Par défaut
    Oui, merci pour ta réponse. Mais en fait faire une flèche verticale ne me suffit pas. Il faut que je la trace dans toutes les directions et que je fasse apparaître un "fantôme" pendant que je la trace. Le moyen le plus simple est encore ce que j'ai fait je pense. En applicant des transfos affines, un peu de matrices de rotations, de translation plane et un petit Flip car en récupérant l'angle de la flèche pour faire ma rotation je fait un petit :
    Mais comme tout le monde le sait l'arctan est donné entre -Pi/2 et Pi/2.
    Enfin voilà, merci quand même mais maintenant ca marche très bien.

  5. #5
    Membre actif Avatar de schneidb
    Profil pro
    Inscrit en
    Janvier 2005
    Messages
    236
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2005
    Messages : 236
    Points : 240
    Points
    240
    Par défaut
    je ne permet de faire un petit up. Je suis dans un cas similaire où j'ai 2 boîtes reliées par un trait, et sur ce trait je voudrais dessiner une flèche au bout.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
          Vector<Shape> shapes = path.getShapes();
          Line2D.Double lastLine = (Line2D.Double)shapes.get( shapes.size() - 1);
          double w = lastLine.getX2() - lastLine.getX1() ;
          double h =   lastLine.getY2() - lastLine.getY1() ;
     
          double radians = Math.atan( h / w);

    J'arrive à récupérer l'angle, et ensuite j'essaye de calculer un point ayant une abscisse éloigné de 5 par rapport à mon point lastLine. Mais rien n'y fait calcul du coef directeur, sinus, cosinus... à chaque fois ya qqch de pas bon, je m'y perds

  6. #6
    Rédacteur/Modérateur

    Avatar de bouye
    Homme Profil pro
    Information Technologies Specialist (Scientific Computing)
    Inscrit en
    Août 2005
    Messages
    6 840
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 47
    Localisation : Nouvelle-Calédonie

    Informations professionnelles :
    Activité : Information Technologies Specialist (Scientific Computing)
    Secteur : Agroalimentaire - Agriculture

    Informations forums :
    Inscription : Août 2005
    Messages : 6 840
    Points : 22 854
    Points
    22 854
    Billets dans le blog
    51
    Par défaut
    Moi j'ai fait un truc comme ca pour determiner l'angle d'un segment par rapport a l'axe horizontal.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
     
      /** Gets the angle between the given vector and the horizontal axis.
       * @param x1 The X coordinate of the first point.
       * @param y1 The Y coordinate of the first point.
       * @param x2 The X coordinate of the first point.
       * @param y2 The Y coordinate of the first point.
       * @return A value within the <CODE>[0, 2*PI[</CODE> range.
       * @exception ValueNotDefinedException If the vector's length is zero, the angle is not defined.
       * @since 1.1
       */
      public static double calculateAngle(double x1, double y1, double x2, double y2) throws ValueNotDefinedException {
        double a = (x2 - x1);
        double b = (y2 - y1);
        double length = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
        if (length == 0) {
          throw new ValueNotDefinedException();
        }
        double p = length; //Math.sqrt(a*a+b*b);
        double theta = Math.asin(Math.abs(b) / p);
        if (b < 0) {
          theta = -theta;
        }
        if (a < 0) {
          theta = Math.PI - theta;
        }
        // Rescale into [0, 2*PI[.
        theta %= 2 * Math.PI;
        if (theta < 0) {
          theta += 2 * Math.PI;
        }
        return theta;
      }
    C'est bien la methode de Galima qui est la plus pratique. Dans la majorite des dessins 2D plutot que de s'embeter a calculer les coordonnes des points apres divers transfomations on dessine le plus simple et on applique les transformations necessaires pour avoir le resultat final apres.

    Ex dans le cas de la tete de fleche :
    - on dessine une ligne representant le segment.
    - on se translate a l'extremite du segment de la fleche.
    - on se rotationne de l'angle correspondant a la pente et a la direction du segment.
    - on dessine un triangle a l'horizontale dont la pointe est a (0, 0)* et les 2 autres sommets ont des abscisses negatives ; ex (-2, 1) et (-2, -1).
    - on applique la rotation inverse.
    - on applique la translation inverse
    Et voila on a une jolie fleche.

    *l'origine du repere actuel = l'extremite du segment, l'axe X est maintenant // au segment grace a la rotation.
    Merci de penser au tag quand une réponse a été apportée à votre question. Aucune réponse ne sera donnée à des messages privés portant sur des questions d'ordre technique. Les forums sont là pour que vous y postiez publiquement vos problèmes.

    suivez mon blog sur Développez.

    Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the universe trying to produce bigger and better idiots. So far, the universe is winning. ~ Rich Cook

  7. #7
    Membre actif Avatar de schneidb
    Profil pro
    Inscrit en
    Janvier 2005
    Messages
    236
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2005
    Messages : 236
    Points : 240
    Points
    240
    Par défaut
    j'ai un peu de mal à te suivre quand tu dis: " on dessine une ligne representant le segment. "
    Cette ligne je l'ai déjà


    se placer au bout du segment ca c'est facile pour moi via: Line2D.Double lastLine .

    Pour la rotation avec ta méthode j'obtiens quelque chose de bizarre, mais bien compris entre 0 et 2pi.

    ensuite je suis un peu paumé.

    Par contre j'ai avancé en utilisant le code suivant:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    Graphics2D g2 = (Graphics2D) g;
     
           Vector<Shape> shapes = path.getShapes();       
           Line2D.Double lastLine = (Line2D.Double)shapes.get( shapes.size() - 1);
           double w = lastLine.getX2() - lastLine.getX1() ;
           double h =   lastLine.getY2() - lastLine.getY1() ;
     
          /* double angle = calculateAngle( lastLine.getX1() , lastLine.getY1() , lastLine.getX2(),
                            lastLine.getY2()) ;
           */
     
        double angle = Math.atan( h / w);
     
           System.out.println("angle=" + angle   );
     
           Polygon arrow = new Polygon();       
           arrow.addPoint((int) lastLine.getX2(), (int) lastLine.getY2());
           arrow.addPoint((int) lastLine.getX2() - 10, (int) lastLine.getY2() + 5);
           arrow.addPoint((int) lastLine.getX2() - 10, (int) lastLine.getY2() - 5);
     
           AffineTransform tx = new AffineTransform();
           tx.rotate(angle);   
           Shape arrowRotate = tx.createTransformedShape(arrow);
     
           AffineTransform tx2 = new AffineTransform();
          // tx2.rotate(-angle);
           Shape arrowRotate2 = tx2.createTransformedShape(arrowRotate);
           g2.fill(arrowRotate2 );
    voici ce que j'obtiens, je pense ne pas être loin:


    quand la ligne est horizontale c bon, par contre quand le trait s'incline l'origine de la flèche n'est pas bonne, mais l'angle de rotation est bon, car elle est // au segment

    merci d'avance

  8. #8
    Rédacteur/Modérateur

    Avatar de bouye
    Homme Profil pro
    Information Technologies Specialist (Scientific Computing)
    Inscrit en
    Août 2005
    Messages
    6 840
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 47
    Localisation : Nouvelle-Calédonie

    Informations professionnelles :
    Activité : Information Technologies Specialist (Scientific Computing)
    Secteur : Agroalimentaire - Agriculture

    Informations forums :
    Inscription : Août 2005
    Messages : 6 840
    Points : 22 854
    Points
    22 854
    Billets dans le blog
    51
    Par défaut
    C'est qu'il doit y a voir une erreur dans ton calcul.

    Note : egalement se souvenir que comme sur l'ecran l'axe des Y va vers le bas, le cercle trigonometrique est le mirroir (par rapport a l'axe des X) de celui qu'on a l'habitude de dessiner sur le papier.

    Un peu de code vaut mieux qu'un long discourt. Tu peux faire tourner la fleche en draggant avec la souris.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
     
    package test;
     
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.event.*;
     
    /**
     * <p>Title: </p>
     * <p>Description: </p>
     * <p>Copyright: Copyright (c) 2005</p>
     * <p>Company: </p>
     * @author Fabrice Bouyé (fabriceb@spc.int)
     * @version 1.0
     */
    public class ArrowPanel extends JPanel implements ComponentListener, MouseInputListener {
      /** Default width.
      */
      public static final int DEFAULT_WIDTH = 300;
     
      /** Default height.
      */
      public static final int DEFAULT_HEIGHT = 300;
     
      /** Default size.
      */
      public static final Dimension DEFAULT_SIZE = new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);
     
      /** Starting angle.
      */
      public static final double DEFAULT_ANGLE = Math.PI / 4.0;
     
      /** Labels for angles around the trigonometric circle.
      */
      private static final String[] ANGLE_LABELS = new String[] {"0", "\u03C0/2", "\u03C0", "3*\u03C0/2"};
     
      /** The trigonometric circle shape.
      */
      private Ellipse2D.Double circle = new Ellipse2D.Double();
     
      /** Current segment angle vs X axis.
      */
      private double angle = DEFAULT_ANGLE;
     
      /** Current segment.
      */
      private Line2D.Double segment = new Line2D.Double();
     
      /** Creates a new instance.
       */
      public ArrowPanel() {
        super();
        addComponentListener(this);
        addMouseListener(this);
        addMouseMotionListener(this);
        setPreferredSize(DEFAULT_SIZE);
        setSize(DEFAULT_SIZE);
      }
     
      /** {@inheritDoc}
       */
      @Override protected void paintComponent(Graphics graphics) {
        super.paintComponent(graphics);
        Dimension size = getSize();
        Insets insets = getInsets();
        int width = size.width - (insets.left + insets.right);
        int height = size.height - (insets.top + insets.bottom);
        Graphics2D g2 = (Graphics2D) graphics.create(insets.left, insets.top, width, height);
        g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        try {
          paintAxis(g2, width, height);
          paintCircle(g2, width, height);
          paintArrow(g2, width, height);
        } finally {
          g2.dispose();
        }
      }
     
      /** Paint the axis.
       * @param graphics The graphics context in which to render.
       * @param width The width of the drawing area.
       * @param height The height of the drawing area.
       */
      private void paintAxis(Graphics2D graphics, int width, int height) {
        graphics.setColor(Color.GRAY);
        int centerX = (int) (circle.getX() + circle.getWidth() / 2.0);
        int centerY = (int) (circle.getY() + circle.getHeight() / 2.0);
        graphics.drawLine(0, centerY, width, centerY);
        graphics.drawLine(centerX, 0, centerX, height);
      }
     
      /** Paint the circle.
       * @param graphics The graphics context in which to render.
       * @param width The width of the drawing area.
       * @param height The height of the drawing area.
       */
      private void paintCircle(Graphics2D graphics, int width, int height) {
        graphics.setColor(Color.BLACK);
        graphics.draw(circle);
        int centerX = (int) (circle.getX() + circle.getWidth() / 2.0);
        int centerY = (int) (circle.getY() + circle.getHeight() / 2.0);
        int radius = (int) circle.getWidth() / 2;
        // Draw angle labels around the circle.
        graphics.translate(centerX, centerY);
        AffineTransform transform = AffineTransform.getRotateInstance(Math.PI / 2.0);
        Point2D.Double point = new Point2D.Double(radius + 20, 0);
        for (int i = 0; i < 4; i++) {
          graphics.drawString(ANGLE_LABELS[i], (float) point.x, (float) point.y);
          transform.transform(point, point);
        }
        graphics.translate( -centerX, -centerY);
      }
     
      /** Paint the arrow.
       * @param graphics The graphics context in which to render.
       * @param width The width of the drawing area.
       * @param height The height of the drawing area.
       */
      private void paintArrow(Graphics2D graphics, int width, int height) {
        graphics.setColor(Color.BLUE);
        graphics.draw(segment);
        drawArrowHeadAtLocation(graphics, segment.getX2(), segment.getY2(), angle);
      }
     
      /** Paint the arrow head at given location and angle.
       * @param graphics The graphics context in which to render.
       * @param x The X coordinate.
       * @param y the Y coordinate.
       * @param angle The angle (in radian).
       */
      private void drawArrowHeadAtLocation(Graphics2D graphics, double x, double y, double angle) {
        graphics.translate(x, y);
        graphics.rotate(angle);
        drawArrowHead(graphics);
        graphics.rotate( -angle);
        graphics.translate( -x, -y);
      }
     
      /** Draw a simple arrow head at (0, 0) that points to the right.
       * @param graphics The graphics context in which to render.
       */
      private void drawArrowHead(Graphics2D graphics) {
        graphics.drawLine(0, 0, -10, 5);
        graphics.drawLine(0, 0, -10, -5);
        graphics.drawLine( -10, 5, -10, -5);
      }
     
      ///////////////
      // Geometry. //
      ///////////////
     
      /** Recalculate all shapes with given drawing area dimension.
       * @param width The width of the drawing area.
       * @param height The height of the drawing area.
       */
      private void recalculateShapes(double width, double height) {
        double centerX = width / 2.0;
        double centerY = height / 2.0;
        double radius = Math.min(width / 2.0, height / 2.0) / 2.0;
        circle.setFrameFromCenter(centerX, centerY, centerX + radius, centerY + radius);
        double arrowLength = radius * 1.33;
        double endX = centerX + arrowLength;
        double endY = centerY;
        AffineTransform transform = AffineTransform.getRotateInstance(angle, centerX, centerY);
        Point2D endPoint = transform.transform(new Point2D.Double(endX, endY), null);
        segment.setLine(centerX, centerY, endPoint.getX(), endPoint.getY());
      }
     
      /** Reset the segment's angle relative to a give mouse event.
       * @param event The mouse event.
       */
      private void resetAngleRelativeToEvent(MouseEvent event) {
        Insets insets = getInsets();
        int x = event.getX() - insets.left;
        int y = event.getY() - insets.top;
        resetAngleRelativeToLocation(x, y);
      }
     
      /** Reset the segment's angle relative to a given location.
       * @param locationX The X coordinate.
       * @param locationY The Y corrdinate.
       */
      private void resetAngleRelativeToLocation(double locationX, double locationY) {
        try {
          int centerX = (int) (circle.getX() + circle.getWidth() / 2.0);
          int centerY = (int) (circle.getY() + circle.getHeight() / 2.0);
          // Angle between (center, location) and X axis.
          double newAngle = calculateAngle(centerX, centerY, locationX, locationY);
          AffineTransform transform = AffineTransform.getRotateInstance(newAngle - angle, centerX, centerY);
          Point2D endPoint = transform.transform(segment.getP2(), null);
          segment.setLine(centerX, centerY, endPoint.getX(), endPoint.getY());
          angle = newAngle;
        }
    // Silently consume exception.
        catch (Throwable t) {
        }
      }
     
      /////////////////////
      // static methods. //
      /////////////////////
     
      /** Self-test main.
       * @param args Arguments from the command line.
       */
      public static void main(String ...args) {
        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new ArrowPanel(), BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
      }
     
      /** Gets the angle between the given vector and the horizontal axis.
       * @param x1 The X coordinate of the first point.
       * @param y1 The Y coordinate of the first point.
       * @param x2 The X coordinate of the first point.
       * @param y2 The Y coordinate of the first point.
       * @return A value within the <CODE>[0, 2*PI[</CODE> range.
       * @exception ValueNotDefinedException If the vector's length is zero, the angle is not defined.
       * @since 1.1
       */
      public static double calculateAngle(double x1, double y1, double x2, double y2) throws ValueNotDefinedException {
        double a = (x2 - x1);
        double b = (y2 - y1);
        double length = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
        if (length == 0) {
          throw new ValueNotDefinedException();
        }
        double p = length; //Math.sqrt(a*a+b*b);
        double theta = Math.asin(Math.abs(b) / p);
        if (b < 0) {
          theta = -theta;
        }
        if (a < 0) {
          theta = Math.PI - theta;
        }
        // Rescale into [0, 2*PI[.
        theta %= 2 * Math.PI;
        if (theta < 0) {
          theta += 2 * Math.PI;
        }
        return theta;
      }
     
      ///////////////////////
      // Event management. //
      ///////////////////////
     
      // ComponentListener interface.
     
      /** {@inheritDoc}
       */
      public void componentResized(ComponentEvent event) {
        Dimension size = getSize();
        Insets insets = getInsets();
        int width = size.width - (insets.left + insets.right);
        int height = size.height - (insets.top + insets.bottom);
        recalculateShapes(width, height);
        repaint();
      }
     
      /** {@inheritDoc}
       */
      public void componentMoved(ComponentEvent event) {
      }
     
      /** {@inheritDoc}
       */
      public void componentShown(ComponentEvent event) {
      }
     
      /** {@inheritDoc}
       */
      public void componentHidden(ComponentEvent event) {
      }
     
      // MouseInputListener interface.
     
      /** {@inheritDoc}
       */
      public void mouseClicked(MouseEvent event) {
      }
     
      /** {@inheritDoc}
       */
      public void mousePressed(MouseEvent event) {
        resetAngleRelativeToEvent(event);
        repaint();
      }
     
      /** {@inheritDoc}
       */
      public void mouseReleased(MouseEvent event) {
      }
     
      /** {@inheritDoc}
       */
      public void mouseEntered(MouseEvent event) {
      }
     
      /** {@inheritDoc}
       */
      public void mouseExited(MouseEvent event) {
      }
     
      /** {@inheritDoc}
       */
      public void mouseDragged(MouseEvent event) {
        resetAngleRelativeToEvent(event);
        repaint();
      }
     
      /** {@inheritDoc}
       */
      public void mouseMoved(MouseEvent event) {
      }
     
      ////////////////////
      // Inner classes. //
      ////////////////////
     
      /**
       * <p>Title: </p>
       * <p>Description: </p>
       * <p>Copyright: Copyright (c) 2005</p>
       * <p>Company: </p>
       * @author Fabrice Bouyé (fabriceb@spc.int)
       * @version 1.0
       */
      public static class ValueNotDefinedException extends Exception {}
    }
    Merci de penser au tag quand une réponse a été apportée à votre question. Aucune réponse ne sera donnée à des messages privés portant sur des questions d'ordre technique. Les forums sont là pour que vous y postiez publiquement vos problèmes.

    suivez mon blog sur Développez.

    Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the universe trying to produce bigger and better idiots. So far, the universe is winning. ~ Rich Cook

  9. #9
    Membre confirmé
    Avatar de Glob
    Homme Profil pro
    Architecte de système d'information
    Inscrit en
    Avril 2002
    Messages
    428
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 47
    Localisation : Suisse

    Informations professionnelles :
    Activité : Architecte de système d'information

    Informations forums :
    Inscription : Avril 2002
    Messages : 428
    Points : 630
    Points
    630
    Par défaut
    Hello.
    J'ai pas lu tout les messages. J'ai néanmoins vu qu'il y avait des atan qui traînaient par endroits...

    Je me permets de conseiller de lire la javadoc de la méthode Math.atan2 qui est 'achement utile pour convertir des coordonnées rectangulaires en polaires sans se prendre le chou...

    ++
    Glob
    What would you do if you were not afraid?

    Cours et tutoriels pour apprendre Java , FAQ Java, et Forum Java

  10. #10
    Membre actif Avatar de schneidb
    Profil pro
    Inscrit en
    Janvier 2005
    Messages
    236
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2005
    Messages : 236
    Points : 240
    Points
    240
    Par défaut
    un très grand merci à tous, je suis arrivé au résultat attendu :trouve:

  11. #11
    En attente de confirmation mail

    Homme Profil pro
    Inscrit en
    Décembre 2003
    Messages
    219
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Canada

    Informations forums :
    Inscription : Décembre 2003
    Messages : 219
    Points : 108
    Points
    108
    Par défaut
    Bonjour schneidb
    Comment as-tu finalement fais ? J'ai ce probleme actuellement et en utilisant ton principe, j'ai le meme decallage.

    Merci bien

  12. #12
    En attente de confirmation mail

    Homme Profil pro
    Inscrit en
    Décembre 2003
    Messages
    219
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Canada

    Informations forums :
    Inscription : Décembre 2003
    Messages : 219
    Points : 108
    Points
    108
    Par défaut
    C'est bon je l'ai fait.

  13. #13
    Modérateur
    Avatar de Flaburgan
    Homme Profil pro
    Développeur Web
    Inscrit en
    Avril 2010
    Messages
    1 229
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Isère (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Avril 2010
    Messages : 1 229
    Points : 3 579
    Points
    3 579
    Par défaut
    Je me permets un up (moins gros que celui d'avant 2006 -> 2011, mais quand même) car il me paraît bizarre qu'en java il n'y ait pas de classe prédéfinie qui contient une méthode toute faite pour tracer une flêche en mode drawArrow(Point source, Point destination) ...
    Personne ne connaitrait un package contenant ça ?
    "Historiquement, techniquement, économiquement et moralement, Internet ne peut pas être contrôlé. Autant s’y faire." Laurent Chemla

    Je soutiens Diaspora*, le réseau social libre.

    Veillez à porter une attention toute particulière à l'orthographe...

    Blog collaboratif avec des amis : http://geexxx.fr

    Mon avatar a été fait par chiqitos, merci à lui !

  14. #14
    Modérateur
    Avatar de Flaburgan
    Homme Profil pro
    Développeur Web
    Inscrit en
    Avril 2010
    Messages
    1 229
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Isère (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Avril 2010
    Messages : 1 229
    Points : 3 579
    Points
    3 579
    "Historiquement, techniquement, économiquement et moralement, Internet ne peut pas être contrôlé. Autant s’y faire." Laurent Chemla

    Je soutiens Diaspora*, le réseau social libre.

    Veillez à porter une attention toute particulière à l'orthographe...

    Blog collaboratif avec des amis : http://geexxx.fr

    Mon avatar a été fait par chiqitos, merci à lui !

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Le bout d'une barbe ou comment dessiner une flèche
    Par ptyxs dans le forum Mathématiques
    Réponses: 23
    Dernier message: 14/04/2009, 11h05
  2. Dessiner une flèche
    Par Med Fateh dans le forum 2D
    Réponses: 1
    Dernier message: 27/03/2009, 12h03
  3. Dessiner une flèche dans un QCanvas ?
    Par nouncyr dans le forum Qt
    Réponses: 33
    Dernier message: 29/08/2008, 11h53
  4. Comment dessiner une fléche comme ceci ?
    Par jlassiramzy dans le forum AWT/Swing
    Réponses: 6
    Dernier message: 24/04/2007, 02h57
  5. Comment dessiner une flèche ?
    Par Amine_sas dans le forum 2D
    Réponses: 4
    Dernier message: 20/12/2006, 21h58

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo