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

Graphisme Java Discussion :

Probleme d'affichage fleche


Sujet :

Graphisme Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre averti
    Inscrit en
    Mai 2006
    Messages
    15
    Détails du profil
    Informations forums :
    Inscription : Mai 2006
    Messages : 15
    Par défaut Probleme d'affichage fleche
    Bonjour à tous.
    J'ai un probleme avec mon code qui me dessine un graphe.
    Le code marchait tres bien, ça se dessinait, redessinait encore et encore de façon nickel.
    Le probleme est j'ai voulu rajouter des fleches. J'ai utilisé un bout de code trouvé sur ce forum, je l'ai légérement adapté pour que ça marche. Et là quelque chose de bizarre se passe.
    Le graphe s'affiche tres bien la première fois. La seconde aussi. Mais aprés ça, aléatoirement, il n'affiche les fleches en plusieurs morceaux. Par exemple, imaginons 3 sommets A, B et C et une fleche de B à A et de C à A. L'affichage est bon. Ensuite je demande à afficher que la fleche de B vers A. Et là, la tete de la fleche est relié au bon sommet (A), mais la queue de la fleche part de C.

    Petite précision : si je supprime les fleches et ne laisse que les traits, l'affichage est parfait.

    Donc voilà je vous mets le code, si vous voyez une connerie.

    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
    public class Dessin_Graphe extends Super_Panel implements MouseListener,MouseMotionListener,Dessin_Listener{
     
        /** La variable representant le graphe à afficher */
        private GrapheListe graphe;
        /** La variable autorisant ou non les modifications du graphe. */
        private boolean modifPossible;
     
        protected final static Stroke lien_stroke = new BasicStroke(2.5f);  //largeur du trait pour les liens
        protected final static Stroke basic_stroke = new BasicStroke();      //stroke par defaut
     
        private final static Color couleurFond = Color.lightGray;
        private final static Color couleurVille = Color.GREEN;
        private final static Color couleurArc = Color.BLACK;
        private final static Color couleurTexte = Color.darkGray;
        private final static int villeHaut = 15;
        private final static int villeLarg = 15;
     
        protected final static Font policeTexte = new  Font("Arial", Font.BOLD, 14);     //police pour les noms des villes
        protected final static Font policeDistance = new  Font("Arial", Font.PLAIN, 12);     //police pour les distances
     
        /** La variable representant le controleur IHM que le dessin doit connaitre. */
        protected Controleur_IHM c_IHM;
     
        private static  final   int default_image_type=     BufferedImage.TYPE_INT_ARGB;    //type de l'image pour l'affichage 
        private BufferedImage   buf_Img;        //pour le rendu
        private Graphics2D      gra_Img;       //pour le rendu
        private Dimension   default_size;
        protected int largeur,hauteur;    //dimension 
        private Line2D.Double segment = new Line2D.Double();
          /** Current segment angle vs X axis.
      */  /** Starting angle.
      */
      public static final double DEFAULT_ANGLE = Math.PI / 4.0;
      private double angle = DEFAULT_ANGLE;
     
     
        /**
         * Creates a new instance of Dessin_Graphe
         */
        public Dessin_Graphe(Gestionnaire_BD gBD, Object c) {
            super(gBD);
            this.graphe = new GrapheListe();
            this.c_IHM = (Controleur_IHM) c;
            this.c_IHM.set_Dessin(this);
            this.setBackground(Color.GRAY);
            addMouseListener(this);
            addMouseMotionListener(this);
            this.hauteur = this.HEIGHT;
            this.largeur = this.WIDTH;
            this.setPreferredSize(new Dimension(largeur,hauteur));
        }
     
        public void initDim(){
            Dimension d = this.getSize();
            this.hauteur = d.width;
            this.largeur = d.height;
        }
     
        public void update(Graphics g){
            paint(g);
        }
     
        public void paintComponent(Graphics g ){
            super.paintComponent(g);
            Graphics2D g2D = (Graphics2D) g;
            this.initDim();        
            //création du buffer si il n'existe pas
            if(gra_Img ==  null){
                buf_Img = new BufferedImage(hauteur,largeur,default_image_type);
                buf_Img.setAccelerationPriority(1.0f);
                gra_Img = (Graphics2D) buf_Img.getGraphics();
            }        
            this.optionDeRendu(g2D);
            this.dessinerFond();
            this.dessinerGraphe();
            g2D.drawImage(buf_Img,0,0,this);
            g2D.dispose();
        }
     
        public void optionDeRendu(Graphics2D g2D){
             /** Désactivation de l'anti-aliasing */
            g2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
            g2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
            /** Demande de rendu rapide */
            g2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
            g2D.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_SPEED);
            g2D.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_OFF);
            g2D.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE);
        }
     
        public void dessinerGraphe(){
           Iterator it2 = this.graphe.sommets.iterator();
           while (it2.hasNext()){
               Sommet sommet = (Sommet) it2.next();
               Iterator it3 = sommet.arcsSucc.iterator();
               while(it3.hasNext()){
                    Arc a = (Arc) it3.next();
                    this.dessinerRoute(a);
               }
           }
           Iterator it = this.graphe.sommets.iterator();
           while(it.hasNext()){
               Sommet som = (Sommet) it.next();
               this.dessinerVille(som);           
           }
       }
     
        /**
         * Fonction permettant de dessiner une ville avec la couleur spécifiée
         * @param som Le sommet correspondant à la ville qu'il faut dessiner.
         * @param g2d Le graphique sur lequel on va dessiner
         **/
       public void dessinerVille(Sommet som){
            //l'image de la ville
            gra_Img.setColor(couleurVille);
            gra_Img.fillOval(som.getPosX(), som.getPosY(), villeLarg,villeHaut);
            gra_Img.setColor(Color.WHITE);
            gra_Img.drawOval(som.getPosX(), som.getPosY(), villeLarg,villeHaut);
     
            //le texte
            gra_Img.setFont(policeTexte);
            int w = gra_Img.getFontMetrics().stringWidth(som.getNom());
            int h = gra_Img.getFontMetrics().getHeight()/4;
            gra_Img.setColor(couleurTexte);
            gra_Img.drawString(som.getNom(),som.getPosX()- w/2+villeLarg/2,som.getPosY()+ h + villeHaut/2);
       }
     
        /**
         * Fonction permettant de dessiner un arc entre deux villes
         * @param a Arc à dessiner
         * @param g2d Graphique dans lequel il faudra dessiner l'arc
         */
       public void dessinerRoute(Arc a){        
             gra_Img.setStroke(lien_stroke); 
     
            gra_Img.setFont(policeDistance);
            FontMetrics fm = gra_Img.getFontMetrics();
            /*int h = fm.getHeight();
           
            int x1 = a.getS1().getPosX() + villeLarg/2;
            int y1 = a.getS1().getPosY() + villeHaut/2;
                        
            int x2 = a.getS2().getPosX() + villeLarg/2;
            int y2 = a.getS2().getPosY() + villeHaut/2;
            
            gra_Img.setColor(couleurArc); 
            
            Line2D.Float l= new Line2D.Float(x1,y1,x2,y2);
            gra_Img.draw(l);
            
            //gra_Img.drawLine(x1,y1,x2,y2); 
            
            //affichage de la distance
            //position du texte
            String  txt = "("+ a.getDeb() + "," + a.getCout()+")";
            int xd = (x1+x2)/2 - gra_Img.getFontMetrics().stringWidth(txt)/2;
            int yd = (y1+y2)/2 - gra_Img.getFontMetrics().getHeight()/4;
            
            gra_Img.setColor(couleurTexte);
            gra_Img.drawString(txt,xd,yd);
            
            gra_Img.setStroke(basic_stroke);*/
           int x1 = a.getS1().getPosX() + villeLarg/2;
            int y1 = a.getS1().getPosY() + villeHaut/2;
            int x2 = a.getS2().getPosX() + villeLarg/2;
            int y2 = a.getS2().getPosY() + villeHaut/2;
           this.paintArrow(x1,y1,x2,y2);
     
                   //affichage de la distance
            //position du texte
            String  txt = "("+ a.getDeb() + "," + a.getCout()+")";
            int xd = (x1+x2)/2 - gra_Img.getFontMetrics().stringWidth(txt)/2;
            int yd = (y1+y2)/2 - gra_Img.getFontMetrics().getHeight()/4;
     
            gra_Img.setColor(couleurTexte);
            gra_Img.drawString(txt,xd,yd);
     
            gra_Img.setStroke(basic_stroke);
       }
     
         /** 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(int x1, int y1,int x2, int y2) {
        gra_Img.setColor(couleurArc); 
        gra_Img.draw(segment);
        resetAngleRelativeToLocation(x1, y1,x2,y2);
        drawArrowHeadAtLocation(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( double x, double y, double angle) {
        gra_Img.translate(x, y);
        gra_Img.rotate(angle); 
        drawArrowHead();
        gra_Img.rotate( -angle);
        gra_Img.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() {
            Polygon arrow = new Polygon();       
            arrow.addPoint(-7, 0);
            arrow.addPoint(- 18,  4);
            arrow.addPoint(- 18, - 4);
     
            AffineTransform tx = new AffineTransform();
            Shape arrowRotate = tx.createTransformedShape(arrow);
            AffineTransform tx2 = new AffineTransform();
            Shape arrowRotate2 = tx2.createTransformedShape(arrowRotate);
            gra_Img.fill(arrowRotate2 );
        }
     
      public static class ValueNotDefinedException extends Exception {}
      /** 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;
      }
     
      /** Reset the segment's angle relative to a given location.
       * @param locationX The X coordinate.
       * @param locationY The Y corrdinate.
       */
      private void resetAngleRelativeToLocation(int x1, int y1,int x2, int y2) {
        try {
          int centerX = x1;
          int centerY = y1;
          // Angle between (center, location) and X axis.
          double newAngle = calculateAngle(centerX, centerY, x2, y2);
          AffineTransform transform = AffineTransform.getRotateInstance(newAngle - angle, centerX, centerY);
          /*Point2D endPoint = transform.transform(segment.getP2(), null);
          segment.setLine(centerX, centerY, endPoint.getX(), endPoint.getY());*/
          segment.setLine(x1, y1, x2,y2);
          angle = newAngle;
        }
    // Silently consume exception.
        catch (Throwable t) {
        }
      }
     
        /**
         * Fonction qui dessine le fond.
         * @param g2d 
         */
        public void dessinerFond(){
            gra_Img.setColor(couleurFond);
            gra_Img.fillRect(0,0,this.hauteur,this.largeur);
        }   
     
        /** Fonction qui met à jour le graphe. 
         * @param graphe Le nouveau graphe à afficher.
         */
        public void nouveau_Graphe(GrapheListe gra, boolean modiPos){        
            this.graphe = gra;
            if(this.modifPossible != modiPos || modiPos == false) {// Si on change de fenetre, on doit redefinir le graphisme.
                gra_Img=null; 
                buf_Img = null;
                this.modifPossible = modiPos;}
            repaint();
        } 
     
    }

  2. #2
    Membre averti
    Inscrit en
    Mai 2006
    Messages
    15
    Détails du profil
    Informations forums :
    Inscription : Mai 2006
    Messages : 15
    Par défaut
    C'est bon j'ai trouvé c'était le calcul de l'angle qui était fait au mauvais endroit!
    Merci quand même!!
    Voilà la correction à faire pour ceux que ça interesse.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
         /** 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(int x1, int y1,int x2, int y2) {
        resetAngleRelativeToLocation(x1, y1,x2,y2);
        gra_Img.setColor(couleurArc); 
        gra_Img.draw(segment);
        drawArrowHeadAtLocation(segment.getX2(), segment.getY2(), angle);
      }

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

Discussions similaires

  1. [VB.NET] Probleme d'affichage entre ListBox/TextBox
    Par Monster77 dans le forum Windows Forms
    Réponses: 3
    Dernier message: 03/08/2004, 11h02
  2. [VB.NET] Probleme d'affichage de controle
    Par mic56 dans le forum Windows Forms
    Réponses: 5
    Dernier message: 09/06/2004, 15h03
  3. xml-xsl-fo : probleme d'affichage d'un tableau
    Par clindoeil dans le forum XSL/XSLT/XPATH
    Réponses: 5
    Dernier message: 12/12/2003, 12h46
  4. [langage] Problème d'affichage
    Par marcoss dans le forum Langage
    Réponses: 3
    Dernier message: 29/08/2003, 13h05
  5. IE [Applet] Plug-in problème d'affichage
    Par Tonton Luc dans le forum JBuilder
    Réponses: 4
    Dernier message: 19/06/2003, 08h28

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