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

AWT/Swing Java Discussion :

Problème d'affichage d'un graphique au lancement de l'application


Sujet :

AWT/Swing Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre confirmé
    Profil pro
    Inscrit en
    Novembre 2003
    Messages
    60
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2003
    Messages : 60
    Par défaut Problème d'affichage d'un graphique au lancement de l'application
    Bonjour,

    je rencontre un probleme pour faire afficher au lancement de mon appli un graphique, je n'y arrive qu'en cliquant sur l'unique JButton du programme, sinon le graphique reste blanc :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
     
    paintComponent(jGraph1.getGraphics());
     
    }
    où la fonction paintComponent est la suivante :

    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
     
    public void paintComponent(Graphics g) {
     
    g2 = (Graphics2D) g;
    int i_space,j_space;
    double x,y,t,d,scale_x,scale_y;
    double xc[]= new double[3];
    double yc[]= new double[3];
     
    i_space=0;
    j_space=0;
    scale_x=380/8;
    scale_y=scale_x;
    x=4*scale_x;
    for(y=0;y<=380;y=y+2)
    {
    if (i_space==0){    
    g2.drawLine((int)x,(int)y,(int)x,(int)(y+2));
    i_space=1;
    } else {i_space=0;}
    }
    y=4*scale_y;
    for(x=0;x<=380;x=x+2)
    {
    if (j_space==0){    
    g2.drawLine((int)x,(int)y,(int)(x+2),(int)y);
    j_space=1;
    } else {j_space=0;}
    }
     
    d=2.5;
    xc[0]=-d*Math.sqrt(3)/6;
    yc[0]=d/2;
    xc[1]=d*Math.sqrt(3)/3;
    yc[1]=0;
     
     
     
    xc[2]=-d*Math.sqrt(3)/6; 
    yc[2]=-d/2;
     
    g2.drawOval((int)((4+(xc[0]-1))*scale_x),(int)((4-(yc[0]+1))*scale_y),2*(int)scale_x,2*(int)scale_y);
    g2.drawOval((int)((4+(xc[1]-1))*scale_x),(int)((4-(yc[1]+1))*scale_y),2*(int)scale_x,2*(int)scale_y);
    g2.drawOval((int)((4+(xc[2]-1))*scale_x),(int)((4-(yc[2]+1))*scale_y),2*(int)scale_x,2*(int)scale_y);
     
         }
    Cette fonction trace un repère (x,y) et 3 cercles équidistants.

    En mettant :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
     
    public class NewJFrame extends JFrame {
     
     
        public NewJFrame() {
            super();        
            initComponents();
            paintComponent(jGraph1.getGraphics());        
     
        }
     
     
    ....
    }
    ça compile bien mais au moment de l'exécution de la gui, on dirait que l'appel de "paintComponent(jGraph1.getGraphics())" ne fait rien.

    Si je déplace cet appel dans la méthode initComponents(), j'obtiens l'erreur suivante:

    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at NewJFrame.paintComponent(NewJFrame.java:59)
    at NewJFrame.initComponents(NewJFrame.java:125)
    at NewJFrame.<init>(NewJFrame.java:34)
    at NewJFrame$3.run(NewJFrame.java:235)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatch
    Event(EventQueue.java:597)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)

    J'ai les variables private suivantes:


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
     
     
        private javax.swing.JButton jButton1;
        private org.jgraph.JGraph jGraph1;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JTextField jTextField1;
        private javax.swing.JTextField jTextField2;
        private java.awt.Graphics2D g2;
    J'utilise NetBeans 6.1 pour réaliser cette gui. La méthode initComponents() est générée automatiquement à partir du design :

    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
     
    private void initComponents() {
     
            jButton1 = new javax.swing.JButton();
            jTextField1 = new javax.swing.JTextField();
            jTextField2 = new javax.swing.JTextField();
            jGraph1 = new org.jgraph.JGraph();
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();        
            jGraph1.setModel(null);
     
     
     
     
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setAlwaysOnTop(true);
     
            jButton1.setText("start");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });
     
    .......
    }
    Le main est le suivant:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                    public void run() {
                    new NewJFrame().setVisible(true);
     
                }
            });
     
        }
    Si quelqu'un pouvait voir ce qui ne va pas pour faire afficher dès le lancement ce graphique sans à avoir à appuyer sur le JButton1, ça serait sympa.

    Merci d'avance pour toute réponse.

  2. #2
    Expert confirmé
    Avatar de sinok
    Profil pro
    Inscrit en
    Août 2004
    Messages
    8 765
    Détails du profil
    Informations personnelles :
    Âge : 45
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Août 2004
    Messages : 8 765
    Par défaut
    Au lieu de faire un appel à
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    paintComponen(jGraph1.getGraphics());
    fais juste un appel à repaint.

    De plus que cette instruction me semble très louche tu essaie de dessiner ton composant sur les graphics d'un autre....

    De toute façon pour des opérations de dessin comme celle ci le getGraphics est à banir

  3. #3
    Membre éclairé Avatar de leminipouce
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Janvier 2004
    Messages
    754
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : Agroalimentaire - Agriculture

    Informations forums :
    Inscription : Janvier 2004
    Messages : 754
    Par défaut
    Pour ta NullPointerException, c'est très simple. Au moment où tu fais appel à paintComponent dans initComponents, jGraph1 n'est pas encore initialisé. Il vaut null et tu cherches à appeler une méthode dessus d'où ton exception.

    Sinon en effet teste ce que vient de te dire Sinok...

  4. #4
    Membre confirmé
    Profil pro
    Inscrit en
    Novembre 2003
    Messages
    60
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2003
    Messages : 60
    Par défaut Probleme d'affichage d'un graphique au lancement de l'application
    Bonsoir,

    j'ai essayé de faire un appel à repaint() comme vous me l'avez suggéré:


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
    public class NewJFrame extends JFrame {
     
     
     
        /** Creates new form NewJFrame */
        public NewJFrame() {
            super();        
            initComponents();
    	repaint();        
     
     
        }
    en renommant la méthode paintComponent par repaint:

    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
     
     
    public void repaint() {
     
     
    int i_space,j_space;
    double x,y,t,d,scale_x,scale_y;
    double xc[]= new double[3];
    double yc[]= new double[3];
     
     
    i_space=0;
    j_space=0;
    scale_x=380/8;
    scale_y=scale_x;
    x=4*scale_x;
    for(y=0;y<=380;y=y+2)
    {
    if (i_space==0){    
    g2.drawLine((int)x,(int)y,(int)x,(int)(y+2));
    i_space=1;
    } else {i_space=0;}
    }
    y=4*scale_y;
    for(x=0;x<=380;x=x+2)
    {
    if (j_space==0){    
    g2.drawLine((int)x,(int)y,(int)(x+2),(int)y);
    j_space=1;
    } else {j_space=0;}
    }
     
     
    d=2.5;
    xc[0]=-d*Math.sqrt(3)/6;
    yc[0]=d/2;
     
    xc[1]=d*Math.sqrt(3)/3;
    yc[1]=0;
     
    xc[2]=-d*Math.sqrt(3)/6; 
    yc[2]=-d/2;
     
    g2.drawOval((int)((4+(xc[0]-1))*scale_x),(int)((4-(yc[0]+1))*scale_y),2*(int)scale_x,2*(int)scale_y);
    g2.drawOval((int)((4+(xc[1]-1))*scale_x),(int)((4-(yc[1]+1))*scale_y),2*(int)scale_x,2*(int)scale_y);
    g2.drawOval((int)((4+(xc[2]-1))*scale_x),(int)((4-(yc[2]+1))*scale_y),2*(int)scale_x,2*(int)scale_y);
     
     
     
         }
    Le probleme est toujours pareil, erreur à l'exécution :

    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at NewJFrame.repaint(NewJFrame.java:60)
    at NewJFrame.<init>(NewJFrame.java:36)
    at NewJFrame$3.run(NewJFrame.java:236)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)

    Je pense que c'est du au fait que je n'instancie pas ma "private" variable
    Graphics2D g2 dans initComponents().

    voici les privates variables générées par le design:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
      // Variables declaration - do not modify//GEN-BEGIN:variables
        private javax.swing.JButton jButton1;
        private org.jgraph.JGraph jGraph1;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JTextField jTextField1;
        private javax.swing.JTextField jTextField2;
        private java.awt.Graphics2D g2;
        // End of variables declaration//GEN-END:variables



    Comment faire le lien entre l'objet JGraph jGraph1 ajouté dans le design et l'objet Graphics2D g2 utilisé par la méthode repaint() décrite plus haut qui permet de dessiner ?

    Je n'ai pas trouvé de Composant Graphics (ou Graphics2D) dans la palette de component du design, c'est pour cela que je suis passé par un component JGraph.

    voici la méthode initComponents() pour plus de précision:

    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
     
    private void initComponents() {
     
            jButton1 = new javax.swing.JButton();
            jTextField1 = new javax.swing.JTextField();
            jTextField2 = new javax.swing.JTextField();
            jGraph1 = new org.jgraph.JGraph();
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();        
            jGraph1.setModel(null);
     
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setAlwaysOnTop(true);
     
            jButton1.setText("start");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });
     
            jTextField1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jTextField1ActionPerformed(evt);
                }
            });
     
     
     
     
     
            jLabel1.setText("    b=");
     
            jLabel2.setText("theta=");
     
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(19, 19, 19)
                                        .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 70, Short.MAX_VALUE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addContainerGap()
                                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addContainerGap()
                                        .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGap(39, 39, 39))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(36, 36, 36)
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(37, 37, 37)
                            .addComponent(jLabel2)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                    .addComponent(jGraph1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addContainerGap(28, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(47, 47, 47)
                            .addComponent(jLabel1)
                            .addGap(18, 18, 18)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(32, 32, 32)
                            .addComponent(jButton1)
                            .addGap(32, 32, 32)
                            .addComponent(jLabel2)
                            .addGap(18, 18, 18)
                            .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                           .addContainerGap()
                            .addComponent(jGraph1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)))
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
     
            pack();        
     
     
        }
    Que faire ? je suis un peu perdu là.

    Merci d'avance.

  5. #5
    Membre confirmé
    Inscrit en
    Mai 2008
    Messages
    126
    Détails du profil
    Informations forums :
    Inscription : Mai 2008
    Messages : 126
    Par défaut
    pourquoi tu n'appelle pas ta fonction jButton1ActionPerformed(java.awt.event.ActionEvent evt) comme si tu appuyais sur la boutton ?????
    tu creer un nouvelle événement et tu l'appelle, tu ne te sert pas de ton event de toute façon !
    a la fin de ton init component tu met ->
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    jButton1ActionPerformed(new ActionEvent());

  6. #6
    Rédacteur/Modérateur

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

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

    Informations forums :
    Inscription : Août 2005
    Messages : 6 909
    Billets dans le blog
    54
    Par défaut
    Oui mais bof quoi, les AbstractButton disposent de la méthode doClick() !
    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 confirmé
    Profil pro
    Inscrit en
    Novembre 2003
    Messages
    60
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2003
    Messages : 60
    Par défaut Probleme d'affichage d'un graphique au lancement de l'application
    Merci beaucoup, j'ai enfin réussi à afficher ce graphique au lancement de la gui. J'ai du enlever dans

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    public static void main(String args[])
    la partie suivante qui est généré automatiquement par NetBeans:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    java.awt.EventQueue.invokeLater(new Runnable() {
              public void run() {
    et y mettre:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
     
    NewJFrame jFrame1=new NewJFrame();    
     
                  jFrame1.setVisible(true);         
                  jFrame1.jButton1.doClick();
    Maintenant, reste à garder ce graphique affiché lors d'un resize de la JFrame.

    Encore merci.

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

Discussions similaires

  1. [XL-2007] Problème d'affichage d'un graphique
    Par Irhok dans le forum Macros et VBA Excel
    Réponses: 3
    Dernier message: 22/05/2014, 08h36
  2. Problème d'affichage des objets graphiques
    Par Johngtrs dans le forum Android
    Réponses: 19
    Dernier message: 31/03/2013, 18h44
  3. [MySQL] problème d'affichage d'un graphique en php sur ma page html
    Par sbenamor dans le forum PHP & Base de données
    Réponses: 7
    Dernier message: 24/05/2011, 17h00
  4. Problème d'affichage avec charte graphique
    Par aminos88 dans le forum Servlets/JSP
    Réponses: 6
    Dernier message: 11/06/2009, 18h21
  5. Réponses: 0
    Dernier message: 05/03/2008, 12h20

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