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 :

Exercice d'application java dans NetBeans création de bulles


Sujet :

AWT/Swing Java

  1. #1
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Janvier 2016
    Messages
    62
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Janvier 2016
    Messages : 62
    Par défaut Exercice d'application java dans NetBeans création de bulles
    Bonjour,

    Afin de compléter mes connaissances en Java, je souhaite faire fonctionner une application Java avec NetBeans en créant avec Swing des bulles de savon qui rebondissent sur les parois et entre-elles.

    Voici mon code où les fonctions Paint et g2d ne fonctionnent pas (il n'y a qu'un objet et les bulles restent statiques) :

    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
    /*
     * To change this license header, choose License Headers in Project Properties.
     * To change this template file, choose Tools | Templates
     * and open the template in the editor.
     */
    package bulles;
     
    import java.awt.BasicStroke;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    import java.awt.EventQueue;
    import java.awt.Point;
    import java.awt.Dimension;
    import java.awt.BorderLayout;
    import java.awt.RenderingHints;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Color;
    import java.awt.GradientPaint;
     
    /**
     *
     * @author
     */
    public class Bulles {
     
        public static void main(String[] args) {
            new Bulles();
        }
     
        // Ball objects
        private Ball[] balls = new Ball[5];
        private int ballCount = 0;
     
        public Bulles() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException ex) {
                    } catch (InstantiationException ex) {
                    } catch (IllegalAccessException ex) {
                    } catch (UnsupportedLookAndFeelException ex) {
                    }
     
                    JFrame frame = new JFrame("Bulles");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLayout(new BorderLayout());
                    Balls balls = new Balls();
                    frame.add(balls);
                    frame.setSize(600, 600);
                    frame.setVisible(true);
     
                    new Thread(new BounceEngine(balls)).start();
     
                }
            });
        }
     
        public static int random(int maxRange) {
            return (int) Math.round((Math.random() * maxRange));
        }
     
        public class Balls extends JPanel {
     
            public Balls() {
     
                for (int index = 0; index < 5; index++) {
                    Ball tempBall = new Ball(new Color(random(255), random(255), random(255)));
                    balls[ballCount] = tempBall;
    		ballCount++;
                }
            }
     
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                for (Ball ball : balls) {
                    ball.paint(g2d);
                }
                g2d.dispose();
            }
     
            public Ball[] getBalls() {
                return balls;
            }
        }
     
        public class BounceEngine implements Runnable {
     
            private Balls parent;
     
            public BounceEngine(Balls parent) {
                this.parent = parent;
            }
     
            @Override
            public void run() {
     
                int width = getParent().getWidth();
                int height = getParent().getHeight();
     
                // Position de départ aléatoire...
                for (Ball ball : getParent().getBalls()) {
                    int x = random(width);
                    int y = random(height);
     
                    Dimension size = ball.getSize();
     
                    if (x + size.width > width) {
                        x = width - size.width;
                    }
                    if (y + size.height > height) {
                        y = height - size.height;
                    }
     
                    ball.setLocation(new Point(x, y));
     
                }
     
                while (getParent().isVisible()) {
     
                    // Redessiner les balles...
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            getParent().repaint();
                        }
                    });
     
                    // dessiner à nouveau quand il y a une modification de position...
                    for (Ball ball : getParent().getBalls()) {
                        move(ball);
                    }
     
                    // vérifier s'il y a collision
                    collision();
     
                    // Ralentissement de la vitesse...
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException ex) {
                    }
     
                }
     
            }
     
            public Balls getParent() {
                return parent;
            }
     
            public void move(Ball ball) {
     
                Point p = ball.getLocation();
                Point speed = ball.getSpeed();
                Dimension size = ball.getSize();
     
                int vx = speed.x;
                int vy = speed.y;
     
                int x = p.x;
                int y = p.y;
     
                if (x + vx < 0 || x + size.width + vx > getParent().getWidth()) {
                    vx *= -1;
                }
                if (y + vy < 0 || y + size.height + vy > getParent().getHeight()) {
                    vy *= -1;
                }
                x += vx;
                y += vy;
     
                ball.setSpeed(new Point(vx, vy));
                ball.setLocation(new Point(x, y));
     
            }
     
            public void collision() {
     
                for(int i = 0; i < ballCount; i++)
                    {
     
                    Point pos1 = balls[i].getLocation();
                    Point speed1 = balls[i].getSpeed();
                    Dimension size1 = balls[i].getSize();
     
                    int vx1 = speed1.x;
                    int vy1 = speed1.y;
     
                    int x1 = pos1.x;
                    int y1 = pos1.y;
     
                        for(int j = i + 1; j < ballCount; j++)
                            {   
                            Point pos2 = balls[j].getLocation();
                            Point speed2 = balls[j].getSpeed();
                            Dimension size2 = balls[j].getSize();
     
                            int vx2 = speed2.x;
                            int vy2 = speed2.y;
     
                            int x2 = pos2.x;
                            int y2 = pos2.y;
     
                            double d = (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2);
     
                            d = Math.sqrt(d);
     
                            if(d < size1.width/2+size2.width/2) {
                                //collision
     
                                vx1 *= -1;
                                vy1 *= -1;
                                vx2 *= -1;
                                vy2 *= -1;
     
                                }
     
                                x1 += vx1;
                                y1 += vy1;
     
                                x2 += vx2;
                                y2 += vy2;
     
                                balls[i].setSpeed(new Point(vx1, vy1));
                                balls[i].setLocation(new Point(x1, y1));
     
                                balls[j].setSpeed(new Point(vx2, vy2));
                                balls[j].setLocation(new Point(x2, y2));
     
                            }
                    }
     
                }
     
        }
     
        public class Ball {
     
            private Color color;
            private Point location;
            private Dimension size;
            private Point speed;
     
            public Ball(Color color) {
     
                setColor(color);
     
                speed = new Point(5, 5);
                size = new Dimension(30, 30);
     
            }
     
            public Dimension getSize() {
                return size;
            }
     
            public void setColor(Color color) {
                this.color = color;
            }
     
            public void setLocation(Point location) {
                this.location = location;
            }
     
            public Color getColor() {
                return color;
            }
     
            public Point getLocation() {
                return location;
            }
     
            public Point getSpeed() {
                return speed;
            }
     
            public void setSpeed(Point speed) {
                this.speed = speed;
            }
     
     	public void paint(Graphics2D g2d) {
    		g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    				RenderingHints.VALUE_ANTIALIAS_ON);
    		g2d.setColor(color);
    		g2d.setStroke(new BasicStroke(3));
                    GradientPaint gradient = new GradientPaint(size.width / 2, 4,
    				color, (size.width) / 2, 4 + size.width, new Color(195,205,215,240));
    		g2d.setPaint(gradient);
     
     
    		g2d.fillOval(4, 4, size.width, size.width);
    		gradient = new GradientPaint(size.width / 25, 4, Color.white,
    				(size.width * 6) / 6, (size.width * 6) / 6, new Color(color
    						.getRed(), color.getGreen(), color
    						.getBlue(), 0));
    		g2d.setPaint(gradient); 
    		g2d.fillOval(size.width / 25, 4, (size.width * 6) / 6,
    				(size.width * 6) / 6);
    	}
        }
    }

    Comment faire en sorte que la fonction Paint crée des bulles en mouvement.


    D'avance merci pour votre aide.

  2. #2
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Janvier 2016
    Messages
    62
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Janvier 2016
    Messages : 62
    Par défaut
    Bonjour,

    J'ai changé mon code afin qu'une image d'une bulle située sur mon disque dur soit affichée à l'écran au clic de la souris.

    J'ai 3 fichiers :

    Main.java :

    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
    package bulle;
     
    import javax.swing.*;
     
    public class Main {
     
    	public static void main(String[] args)
    	{
    		JFrame frame = new JFrame("Bulles");
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(),BoxLayout.Y_AXIS));
     
     
    		Bulles bulleCanvas = new Bulles();
     
    		frame.getContentPane().add(bulleCanvas);
    		frame.pack();
    		frame.setVisible(true);
     
    		bulleCanvas.start();
     
    	}
     
    }
    Vector2d.java :

    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
    package bulle;
     
    public class Vector2d {
     
    	private float x;
    	private float y;
     
    		public Vector2d(float x, float y)
    	{
    		this.setX(x);
    		this.setY(y);
    	}
     
    		public void setX(float x) {
    		this.x = x;
    	}
     
                    public float getX() {
    		return x;
    	}
     
    		public void setY(float y) {
    		this.y = y;
    	}
     
                    public float getY() {
    		return y;
    	}
     
    }
    Bulles.java :

    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
    /*
     * To change this license header, choose License Headers in Project Properties.
     * To change this template file, choose Tools | Templates
     * and open the template in the editor.
     */
    package bulle;
     
    import com.sun.webkit.graphics.WCImage;
    import static com.sun.webkit.graphics.WCImage.getImage;
    import java.awt.Dimension;
    import java.awt.Canvas;
    import java.awt.RenderingHints;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Color;
    import java.awt.Point;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import java.awt.image.BufferStrategy;
     
    /**
     *
     * @author
     */
    public class Bulles extends Canvas {
     
        // Rendering / Buffer objects
    	private BufferStrategy strategy;
    	private Graphics2D g2;
     
        // Objets Bulles
        private Bulle[] bulles = new Bulle[5000];
        private Bulle tempBulle;
        private Bulle currentBulle;
        private int bulleCount = 0;
     
        public Bulles() {
     
            setPreferredSize(new Dimension(800, 600));
    	setIgnoreRepaint(true);
     
            // Evénement(s) clic
    		MouseHandler mouseHandler = new MouseHandler();
    		addMouseMotionListener(mouseHandler);
    		addMouseListener(mouseHandler); 
                }
     
        	public void start()
    	{
    		mainStart();
    	}
     
            	public void mainStart()
    	{
                while(true)
    		{
                    lance();
                    }
     
            }
     
              	public void lance()
    	{
     
    		if (strategy == null || strategy.contentsLost())
    		{
    			// Creation BufferStrategy pour affichage
    			createBufferStrategy(2);
    			strategy = getBufferStrategy();
    			Graphics g = strategy.getDrawGraphics();
    			this.g2 = (Graphics2D) g;
    		}
     
     
    		this.g2.setRenderingHint (RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
     
    		// Affichage arrière plan
    		this.g2.setColor(Color.WHITE);
    		this.g2.fillRect(0, 0, getWidth(), getHeight());
     
    		// Affichage des objets
    		for(int i = 0; i < bulleCount; i++)
    		{
                        WCImage img = getImage("C:\\Users\\...\\Documents\\NetBeansProjects\\Bulle\\src\\bulle.png");
                        bulles[i].drawImage(img,0,0,new Color(255,255,255),null);
    		}
     
     
      		if (!strategy.contentsLost()) strategy.show();
     
     
     
    	}
     
        	private class MouseHandler extends MouseAdapter implements MouseMotionListener
    	{
    		public void mousePressed(MouseEvent e)
                    {
     
                    tempBulle = new Bulle(e.getX(), e.getY(), 30);
                    tempBulle.setLocation(new Point(e.getX(), e.getY()));
                    }
     
                    public void mouseReleased(MouseEvent e)
                    {
                    bulles[bulleCount] = tempBulle;
    		bulleCount++;
                    }
            }
     
    public class Bulle implements Comparable<Bulle>{
     
    	public Vector2d position;
    	private float radius;
            private Point location;
            private Point speed;
     
    	public Bulle(float x, float y, float radius)
    	{
                    speed = new Point(10 , 10);
    		this.position = new Vector2d(x, y);
    		this.setRadius(radius);
    	}
     
    	public void setRadius(float radius) {
    		this.radius = radius;
    	}
     
    	public float getRadius() {
    		return radius;
    	}
     
            	public int compareTo(Bulle bulle) {
     
                        	if (this.position.getX() - this.getRadius() > bulle.position.getX() - bulle.getRadius())
    		{
    			return 1;
    		}
    		else if (this.position.getX() - this.getRadius() < bulle.position.getX() - bulle.getRadius())
    		{
    			return -1;
    		}
    		else
    		{
    			return 0;
    		}
     
                    }
     
            public void setLocation(Point location) {
                    this.location = location;
            }
     
            public Point getLocation() {
                    return location;
            }
     
            public Point getSpeed() {
                    return speed;
            }
     
            public void setSpeed(Point speed) {
                    this.speed = speed;
            }
     
            private void drawImage(WCImage img, int i, int i0, Color color, Object object) {
     
            }
        }
     
    }
    Voici l'image dont le chemin a été renseigné dans Bulles.java :

    Nom : bulle.png
Affichages : 325
Taille : 133,4 Ko

    Au clic de la souris, rien ne s'affiche. S'agit-il de l'affectation "this.g2" ? Comment faire ?

    Merci pour votre aide

  3. #3
    Rédacteur/Modérateur

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

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

    Informations forums :
    Inscription : Août 2005
    Messages : 6 901
    Billets dans le blog
    54
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    import com.sun.webkit.graphics.WCImage;
    import static com.sun.webkit.graphics.WCImage.getImage;
    Utilisation d'une API interdite détectée...

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    public void mainStart() {
      while(true) {
        lance();
      }
    }
    Allons bon, désormais on a une boucle infinie dans le thread actuel sans pause ménagée et qui laisse jamais le temps au programme de se rafraîchir....

    Ça fait genre 3 fois que je te dis d'aller voir la doc de BufferStrategy. Quel est le soucis ?

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    // Get a new graphics context every time through the loop
    // to make sure the strategy is validated
    Graphics graphics = strategy.getDrawGraphics();
    Ce n'est pas pour rien qu'ils récupèrent le graphics a chaque itération de la boucle, sans chercher a le conserver, le contenu de ce genre de buffer est hautement volatile.

    2 choses manquent cependant dans l'exemple présenté dans la doc de la classe :
    • La mise en place d'un Thread dédié pour faire la boucle ;
    • La pause dans ce thread. Typiquement si on veut faire du 60fps, il faut faire un sleep() durant 1000 * 1 / 60.


    Quand a la théorie du pourquoi du comment il ne faut PAS faire sleep() dans le thread événementiel de AWT / Swing (Event Dispatch Thread ou EDT), voir ici (même si en l’occurrence, la je parlais de JavaFX, le principe est le même).
    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

  4. #4
    Rédacteur/Modérateur

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

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

    Informations forums :
    Inscription : Août 2005
    Messages : 6 901
    Billets dans le blog
    54
    Par défaut
    Ce qui donne lorsqu'on daigne lire la doc:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    package bulle;
     
    public record Vector2d(float x, float y) {
    }
    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
    package bulle;
     
    import javax.imageio.ImageIO;
    import java.awt.*;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import java.awt.image.BufferStrategy;
    import java.awt.image.BufferedImage;
    import java.util.Arrays;
    import java.util.Objects;
    import java.util.Optional;
     
    /**
     * @author
     */
    public class Bulles extends Canvas {
        // Objets Bulles
        private final Bulle[] bulles = new Bulle[5000];
        private Bulle tempBulle;
        private Bulle currentBulle;
        private int bulleCount = 0;
     
        public Bulles() {
     
            setPreferredSize(new Dimension(800, 600));
            setIgnoreRepaint(true);
     
            // Evénement(s) clic
            MouseHandler mouseHandler = new MouseHandler();
            addMouseMotionListener(mouseHandler);
            addMouseListener(mouseHandler);
        }
     
        private Thread thread;
     
        public synchronized void start() {
            Optional.ofNullable(thread)
                    .ifPresent(Thread::interrupt);
            thread = new Thread(this::mainLoop);
            thread.start();
        }
     
        public synchronized void stop() {
            Optional.ofNullable(thread)
                    .ifPresent(Thread::interrupt);
            thread = null;
        }
     
        private static final long SLEEP_TIME = (long) Math.ceil(1000 * (1 / 60d));
     
        private BufferedImage img;
     
        public void mainLoop() {
            try {
                // Preload.
                final var imgUrl = getClass().getResource("bulle.png");
                img = ImageIO.read(imgUrl);
                createBufferStrategy(2);
                final var strategy = getBufferStrategy();
                // Loop.
                // READ THE DOC!!!!!!!!!!!!!!!!
                while (!Thread.currentThread().isInterrupted()) {
                    do {
                        do {
                            final var g = (Graphics2D) strategy.getDrawGraphics();
                            try {
                                lance(g);
                            } finally {
                                g.dispose();
                            }
                        } while (strategy.contentsRestored());
                        strategy.show();
                    } while (strategy.contentsLost());
                    Thread.sleep((long) (1000 * 1 / 60d));
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
     
        public void lance(Graphics2D g) {
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            // Affichage arrière plan
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, getWidth(), getHeight());
            // Affichage des objets
            Arrays.stream(bulles)
                    .filter(Objects::nonNull)
                    .forEach(bulle -> Bulle.drawImage(g, img, bulle.position.x(), bulle.position.y(), null, null));
        }
     
        private class MouseHandler extends MouseAdapter implements MouseMotionListener {
            public void mousePressed(MouseEvent e) {
     
                tempBulle = new Bulle(e.getX(), e.getY(), 30);
                tempBulle.setLocation(new Point(e.getX(), e.getY()));
            }
     
            public void mouseReleased(MouseEvent e) {
                bulles[bulleCount] = tempBulle;
                bulleCount++;
            }
        }
     
        private static class Bulle implements Comparable<Bulle> {
     
            public Vector2d position;
            private float radius;
            private Point location;
            private Point speed;
     
            public Bulle(float x, float y, float radius) {
                speed = new Point(10, 10);
                this.position = new Vector2d(x, y);
                this.setRadius(radius);
            }
     
            public void setRadius(float radius) {
                this.radius = radius;
            }
     
            public float getRadius() {
                return radius;
            }
     
            public int compareTo(Bulle bulle) {
     
                if (this.position.x() - this.getRadius() > bulle.position.x() - bulle.getRadius()) {
                    return 1;
                } else if (this.position.x() - this.getRadius() < bulle.position.x() - bulle.getRadius()) {
                    return -1;
                } else {
                    return 0;
                }
     
            }
     
            public void setLocation(Point location) {
                this.location = location;
            }
     
            public Point getLocation() {
                return location;
            }
     
            public Point getSpeed() {
                return speed;
            }
     
            public void setSpeed(Point speed) {
                this.speed = speed;
            }
     
            private static void drawImage(Graphics2D g2, BufferedImage img, float x, float y, Color color, Object object) {
                g2.drawImage(img, (int) (x - img.getWidth() / 2d), (int) (y - img.getHeight() / 2d), null);
            }
        }
     
    }
    Nom : bubulles.jpg
Affichages : 303
Taille : 122,9 Ko
    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

  5. #5
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Janvier 2016
    Messages
    62
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Janvier 2016
    Messages : 62
    Par défaut
    Merci bouye,

    Je suis débutant en java ... et je tâtonne !

    J'ai ces 3 fichiers :

    Main.java :

    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
    package bulle;
     
    import javax.swing.*;
     
    public class Main {
     
    	public static void main(String[] args)
    	{
    		JFrame frame = new JFrame("Bulles");
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(),BoxLayout.Y_AXIS));
     
     
    		Bulles bulleCanvas = new Bulles();
     
    		frame.getContentPane().add(bulleCanvas);
    		frame.pack();
    		frame.setVisible(true);
     
    		bulleCanvas.start();
     
    	}
     
    }
    Vector2d.java :

    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
    package bulle;
     
    public class Vector2d {
     
    	private float x;
    	private float y;
     
    		public Vector2d(float x, float y)
    	{
    		this.setX(x);
    		this.setY(y);
    	}
     
    		public void setX(float x) {
    		this.x = x;
    	}
     
                    public float getX() {
    		return x;
    	}
     
    		public void setY(float y) {
    		this.y = y;
    	}
     
                    public float getY() {
    		return y;
    	}
     
    }
    Bulles.java :

    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
    /*
     * To change this license header, choose License Headers in Project Properties.
     * To change this template file, choose Tools | Templates
     * and open the template in the editor.
     */
    package bulle;
     
    import javax.imageio.ImageIO;
    import java.awt.Dimension;
    import java.awt.Canvas;
    import java.awt.RenderingHints;
    import java.awt.Graphics2D;
    import java.awt.Color;
    import java.awt.Point;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import java.awt.image.BufferStrategy;
    import java.awt.image.BufferedImage;
    import java.net.URL;
    import java.util.Arrays;
    import java.util.Objects;
    import java.util.Optional;
     
     
    /**
     *
     * @author
     */
    public class Bulles extends Canvas {
     
        // Rendering / Buffer objects
    	private BufferStrategy strategy;
    	private Graphics2D g2;
     
        // Objets Bulles
        private Bulle[] bulles = new Bulle[5000];
        private Bulle tempBulle;
        private Bulle currentBulle;
        private int bulleCount = 0;
     
        public Bulles() {
     
            setPreferredSize(new Dimension(800, 600));
    	setIgnoreRepaint(true);
     
            // Evénement(s) clic
    		MouseHandler mouseHandler = new MouseHandler();
    		addMouseMotionListener(mouseHandler);
    		addMouseListener(mouseHandler); 
                }
     
     private Thread thread;
     
        public synchronized void start() {
            Optional.ofNullable(thread)
                    .ifPresent(Thread::interrupt);
            thread = new Thread(this::mainLoop);
            thread.start();
        }
     
        public synchronized void stop() {
            Optional.ofNullable(thread)
                    .ifPresent(Thread::interrupt);
            thread = null;
        }
     
        private static final long SLEEP_TIME = (long) Math.ceil(1000 * (1 / 60d));
     
        private BufferedImage img;
     
        public void mainLoop() {
            try {
                // Preload.
                final URL imgUrl = getClass().getResource("bulle.png");
                img = ImageIO.read(imgUrl);
                createBufferStrategy(2);
                strategy = getBufferStrategy();
                // Loop.
                // READ THE DOC!!!!!!!!!!!!!!!!
                while (!Thread.currentThread().isInterrupted()) {
                    do {
                        do {
                            Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
                            try {
                                lance(g);
                            } finally {
                                g.dispose();
                            }
                        } while (strategy.contentsRestored());
                        strategy.show();
                    } while (strategy.contentsLost());
                    Thread.sleep((long) (1000 * 1 / 60d));
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
     
              	public void lance(Graphics2D g)
    	{
     
     
    		this.g2.setRenderingHint (RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
     
    		// Affichage arrière plan
    		this.g2.setColor(Color.WHITE);
    		this.g2.fillRect(0, 0, getWidth(), getHeight());
     
    		// Affichage des objets
                    Arrays.stream(bulles)
                    .filter(Objects::nonNull)
                    .forEach(bulle -> Bulle.drawImage(g, img, bulle.position.getX(), bulle.position.getY(), null, null));
     
     
    	}
     
        	private class MouseHandler extends MouseAdapter implements MouseMotionListener
    	{
    		public void mousePressed(MouseEvent e)
                    {
     
                    tempBulle = new Bulle(e.getX(), e.getY(), 30);
                    tempBulle.position = new Vector2d(e.getX(), e.getY());
                    }
     
                    public void mouseReleased(MouseEvent e)
                    {
                    bulles[bulleCount] = tempBulle;
    		bulleCount++;
                    }
            }
     
    public static class Bulle implements Comparable<Bulle>{
     
    	public Vector2d position;
    	private float radius;
            private Point location;
            private Point speed;
     
    	public Bulle(float x, float y, float radius)
    	{
                    speed = new Point(10 , 10);
    		this.position = new Vector2d(x, y);
    		this.setRadius(radius);
    	}
     
    	public void setRadius(float radius) {
    		this.radius = radius;
    	}
     
    	public float getRadius() {
    		return radius;
    	}
     
            	public int compareTo(Bulle bulle) {
     
                        	if (this.position.getX() - this.getRadius() > bulle.position.getX() - bulle.getRadius())
    		{
    			return 1;
    		}
    		else if (this.position.getX() - this.getRadius() < bulle.position.getX() - bulle.getRadius())
    		{
    			return -1;
    		}
    		else
    		{
    			return 0;
    		}
     
                    }
     
            public void setLocation(Point location) {
                    this.location = location;
            }
     
            public Point getLocation() {
                    return location;
            }
     
            public Point getSpeed() {
                    return speed;
            }
     
            public void setSpeed(Point speed) {
                    this.speed = speed;
            }
     
            private static void drawImage(Graphics2D g2, BufferedImage img, float x, float y, Color color, Object object) {
                    g2.drawImage(img, (int) (x - img.getWidth() / 2d), (int) (y - img.getHeight() / 2d), null);
            }
     
        }
     
    }
    Rien ne se passe au clic de la souris pour moi !

  6. #6
    Rédacteur/Modérateur

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

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

    Informations forums :
    Inscription : Août 2005
    Messages : 6 901
    Billets dans le blog
    54
    Par défaut
    Est-ce que par hasard tu as pense a aller voir ta console pour voir si tu m'avais pas une erreur de ce type qui s'affiche ?

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    java.lang.IllegalArgumentException: input == null!
    	at java.desktop/javax.imageio.ImageIO.read(ImageIO.java:1400)
    	at bulle.Bulles.mainLoop(Bulles.java:65)
    	at java.base/java.lang.Thread.run(Thread.java:832)
    Erreur qui arrive car le programme n'arrive pas a trouver l'image. Ou as-tu place ton image d'ailleurs ? Si tu as conserve le meme chemin que dans ton code initial, tu dois modifier mon code pour charge l'image correctement (lire la doc de ImageIO !!!!!!!)
    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é
    Homme Profil pro
    Étudiant
    Inscrit en
    Janvier 2016
    Messages
    62
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Janvier 2016
    Messages : 62
    Par défaut
    Merci bouye,

    J'ai tenté de lire la doc mais sans exemples concrets, mon niveau d'anglais est limité.

    J'ai changé cependant la ligne 75 :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    final URL imgUrl = getClass().getResource("/src/bulle/bulle.png");
    J'ai ce message :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    java.lang.NullPointerException
    	at bulle.Bulles.lance(Bulles.java:104)
    	at bulle.Bulles.mainLoop(Bulles.java:86)
    	at java.lang.Thread.run(Thread.java:748)
    Le projet dans Netbeans est organisé comme ici :

    Nom : capture_ecran.jpg
Affichages : 293
Taille : 18,9 Ko

    Merci pour ton aide.

  8. #8
    Rédacteur/Modérateur

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

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

    Informations forums :
    Inscription : Août 2005
    Messages : 6 901
    Billets dans le blog
    54
    Par défaut
    Certes mais il aurait fallu me dire ce qu'il y avait a la ligne 104 du fichier Bulles.java au cas ou tu avais fais d'autres modifs par rapport a mon code.

    Il ne faut pas hésiter a dire tout de suite justement quand on a des soucis avec l'anglais, ça nous permet de fournir un peu plus d'explications que juste "allez lire la doc tout est écrit dedans".

    Pour charger l'image, étant donné l'organisation de ton projet, tu devrais juste avoir a faire :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    final URL imgUrl = getClass().getResource("bulle.png");
    La résolution des ressources embarquées cherche d'abord dans le package courant quand on ne spécifie pas de chemin.

    Pour info, il existe une variante de la méthode read() qui prend un File en argument ce qui permet de spécifier le chemin vers un fichier non-embarqué qui se trouve ailleurs sur le disque dur.
    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é
    Homme Profil pro
    Étudiant
    Inscrit en
    Janvier 2016
    Messages
    62
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Janvier 2016
    Messages : 62
    Par défaut
    Merci,

    J'ai étudié la question voici mon projet avec une classpath :

    Nom : Capture2.jpg
Affichages : 285
Taille : 16,6 Ko

    Bulles.java :

    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
    /*
     * To change this license header, choose License Headers in Project Properties.
     * To change this template file, choose Tools | Templates
     * and open the template in the editor.
     */
    package bulle;
     
    import javax.imageio.ImageIO;
    import java.awt.Dimension;
    import java.awt.Canvas;
    import java.awt.RenderingHints;
    import java.awt.Graphics2D;
    import java.awt.Color;
    import java.awt.Point;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import java.awt.image.BufferStrategy;
    import java.awt.image.BufferedImage;
    import java.net.URL;
    import java.util.Arrays;
    import java.util.Objects;
    import java.util.Optional;
     
     
    /**
     *
     * @author
     */
    public class Bulles extends Canvas {
     
        // Rendering / Buffer objects
    	private BufferStrategy strategy;
    	private Graphics2D g2;
     
        // Objets Bulles
        private Bulle[] bulles = new Bulle[5000];
        private Bulle tempBulle;
        private Bulle currentBulle;
        private int bulleCount = 0;
     
        public Bulles() {
     
            setPreferredSize(new Dimension(800, 600));
    	setIgnoreRepaint(true);
     
            // Evénement(s) clic
    		MouseHandler mouseHandler = new MouseHandler();
    		addMouseMotionListener(mouseHandler);
    		addMouseListener(mouseHandler); 
                }
     
     private Thread thread;
     
        public synchronized void start() {
            Optional.ofNullable(thread)
                    .ifPresent(Thread::interrupt);
            thread = new Thread(this::mainLoop);
            thread.start();
        }
     
        public synchronized void stop() {
            Optional.ofNullable(thread)
                    .ifPresent(Thread::interrupt);
            thread = null;
        }
     
        private static final long SLEEP_TIME = (long) Math.ceil(1000 * (1 / 60d));
     
        private BufferedImage img;
     
        public void mainLoop() {
            try {
                // Preload.
                final URL imgUrl = getClass().getResource("bulle.png");
                img = ImageIO.read(imgUrl);
                createBufferStrategy(2);
                strategy = getBufferStrategy();
                // Loop.
                // READ THE DOC!!!!!!!!!!!!!!!!
                while (!Thread.currentThread().isInterrupted()) {
                    do {
                        do {
                            Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
                            try {
                                lance(g);
                            } finally {
                                g.dispose();
                            }
                        } while (strategy.contentsRestored());
                        strategy.show();
                    } while (strategy.contentsLost());
                    Thread.sleep((long) (1000 * 1 / 60d));
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
     
              	public void lance(Graphics2D g)
    	{
     
     
    		this.g2.setRenderingHint (RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
     
    		// Affichage arrière plan
    		this.g2.setColor(Color.WHITE);
    		this.g2.fillRect(0, 0, getWidth(), getHeight());
     
    		// Affichage des objets
                    Arrays.stream(bulles)
                    .filter(Objects::nonNull)
                    .forEach(bulle -> Bulle.drawImage(g, img, bulle.position.getX(), bulle.position.getY(), null, null));
     
     
    	}
     
        	private class MouseHandler extends MouseAdapter implements MouseMotionListener
    	{
    		public void mousePressed(MouseEvent e)
                    {
     
                    tempBulle = new Bulle(e.getX(), e.getY(), 30);
                    tempBulle.position = new Vector2d(e.getX(), e.getY());
                    }
     
                    public void mouseReleased(MouseEvent e)
                    {
                    bulles[bulleCount] = tempBulle;
    		bulleCount++;
                    }
            }
     
    public static class Bulle implements Comparable<Bulle>{
     
    	public Vector2d position;
    	private float radius;
            private Point location;
            private Point speed;
     
    	public Bulle(float x, float y, float radius)
    	{
                    speed = new Point(10 , 10);
    		this.position = new Vector2d(x, y);
    		this.setRadius(radius);
    	}
     
    	public void setRadius(float radius) {
    		this.radius = radius;
    	}
     
    	public float getRadius() {
    		return radius;
    	}
     
            	public int compareTo(Bulle bulle) {
     
                        	if (this.position.getX() - this.getRadius() > bulle.position.getX() - bulle.getRadius())
    		{
    			return 1;
    		}
    		else if (this.position.getX() - this.getRadius() < bulle.position.getX() - bulle.getRadius())
    		{
    			return -1;
    		}
    		else
    		{
    			return 0;
    		}
     
                    }
     
            public void setLocation(Point location) {
                    this.location = location;
            }
     
            public Point getLocation() {
                    return location;
            }
     
            public Point getSpeed() {
                    return speed;
            }
     
            public void setSpeed(Point speed) {
                    this.speed = speed;
            }
     
            private static void drawImage(Graphics2D g2, BufferedImage img, float x, float y, Color color, Object object) {
                    g2.drawImage(img, (int) (x - img.getWidth() / 2d), (int) (y - img.getHeight() / 2d), null);
            }
     
        }
     
    }
    Main.java :

    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
    package bulle;
     
    import javax.swing.*;
     
    public class Main {
     
    	public static void main(String[] args)
    	{
    		JFrame frame = new JFrame("Bulles");
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(),BoxLayout.Y_AXIS));
     
     
    		Bulles bulleCanvas = new Bulles();
     
    		frame.getContentPane().add(bulleCanvas);
    		frame.pack();
    		frame.setVisible(true);
     
    		bulleCanvas.start();
     
    	}
     
    }
    Vector2d.java

    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
    package bulle;
     
    public class Vector2d {
     
    	private float x;
    	private float y;
     
    		public Vector2d(float x, float y)
    	{
    		this.setX(x);
    		this.setY(y);
    	}
     
    		public void setX(float x) {
    		this.x = x;
    	}
     
                    public float getX() {
    		return x;
    	}
     
    		public void setY(float y) {
    		this.y = y;
    	}
     
                    public float getY() {
    		return y;
    	}
     
    }
    J'ai ce message en sortie de console :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    java.lang.NullPointerException
    	at bulle.Bulles.lance(Bulles.java:104)
    	at bulle.Bulles.mainLoop(Bulles.java:86)
    	at java.lang.Thread.run(Thread.java:748)
    Je ne comprends pas.

  10. #10
    Rédacteur/Modérateur

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

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

    Informations forums :
    Inscription : Août 2005
    Messages : 6 901
    Billets dans le blog
    54
    Par défaut
    Et donc vu que tu m'as toujours pas dit quelle etait la ligne fautive, j'ai du reprendre le code et le faire tourner a nouveau.

    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
    private Graphics2D g2;
    
    [...]
    
    public void lance(Graphics2D g)
        {
    
    
            this.g2.setRenderingHint (RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    
            // Affichage arrière plan
            this.g2.setColor(Color.WHITE);
            this.g2.fillRect(0, 0, getWidth(), getHeight());
    
            // Affichage des objets
            Arrays.stream(bulles)
                    .filter(Objects::nonNull)
                    .forEach(bulle -> Bulle.drawImage(g, img, bulle.position.getX(), bulle.position.getY(), null, null));
    
    
        }
    Bien sur que g2 est null puisque tu l'initialise jamais (et que de toutes manières tu ne dois pas conserver de référence sur ce Graphics). Je t'ai fourni une version corrigée du code qui passe le Graphics sur lequel il faut dessiner en paramètre de la fonction lance() et c'est tout et ca marche tres bien.


    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
    public void lance(Graphics2D g)
        {
    
    
            g.setRenderingHint (RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    
            // Affichage arrière plan
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, getWidth(), getHeight());
    
            // Affichage des objets
            Arrays.stream(bulles)
                    .filter(Objects::nonNull)
                    .forEach(bulle -> Bulle.drawImage(g, img, bulle.position.getX(), bulle.position.getY(), null, null));
    
    
        }
    Il serait peut-être bon de laisser tomber les tentatives de faire du dessin pour un temps pour apprendre a la place a se servir du débogueur histoire d'aller voir ce que fait ton code lorsqu'il tourne en mettant un breakpoint a la ligne indiquée dans la trace de l'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

  11. #11
    Rédacteur/Modérateur

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

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

    Informations forums :
    Inscription : Août 2005
    Messages : 6 901
    Billets dans le blog
    54
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    java.lang.NullPointerException
    	at bulle.Bulles.lance(Bulles.java:104)
    Quand tu vois ça, tu sais que a la ligne 104 de Bulles.java il y a une variable sur laquelle on invoque une méthode ou qu'on passe en paramètre d'une méthode qui est null alors qu'elle ne devrait pas. Donc soit elle fait échouer un test, soit le programme plante car il s'attendait pas a cette valeur. Donc :

    • Tu vas voir la ligne en question.
    • Tu y places un breakpoint ou juste un peu avant.
    • Tu fais tourner ton code en mode débogage dans ton IDE.
    • Tu atteints la ligne en question quitte a avancer pas a pas si nécessaire dans le code.
    • Tu vérifies quelle variable cause le soucis grâce aux outils qui permettent d'avoir les valeurs des variables pendant que le programme tourne.
    • Et tu essaies de déterminer pourquoi elle a pas la bonne valeur (problème d'initialisation, problème de logique algorithmique, etc.)
    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

  12. #12
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Janvier 2016
    Messages
    62
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Janvier 2016
    Messages : 62
    Par défaut
    Merci.

    Tout est correct maintenant grâce au forum.

    Merci pour ton aide.

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

Discussions similaires

  1. quitter une application java dans un pda
    Par air75 dans le forum Java ME
    Réponses: 1
    Dernier message: 07/03/2008, 16h48
  2. version JAVA dans netbeans
    Par KalKul dans le forum NetBeans
    Réponses: 2
    Dernier message: 15/08/2007, 17h47
  3. Réponses: 5
    Dernier message: 31/07/2007, 16h34
  4. Plug Oracle Application Sever dans NetBeans
    Par supernova dans le forum NetBeans
    Réponses: 8
    Dernier message: 29/05/2007, 17h57
  5. comment faire appel d'une application java dans un script shell?
    Par moradbe dans le forum Shell et commandes GNU
    Réponses: 3
    Dernier message: 01/02/2007, 19h55

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