les threads exemple balls
je suis débutant en java et je suis entraine d'étudier els threads j'ai trouvé ce jeux de ball
est ce que quelq'un peut m'aider a comprendre comment il fonctionne par des commentaires
Code:
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
| import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.ArrayList;
import javax.swing.*;
public class ballon extends JFrame {
private JButton Lancer = new JButton("ajouter ballon");
private JButton Quitter = new JButton("Quitter");
private JPanel boutons = new JPanel();
private Panneau panneau = new Panneau();
public ballon() {
super("NaSrO");
panneau.setBackground(Color.white);
add(panneau);
add(boutons, BorderLayout.SOUTH);
boutons.add(Lancer);
boutons.add(Quitter);
Lancer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ajoutBalle();
}
});
Quitter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
setSize(500, 500);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
private void ajoutBalle() {
Balle balle = new Balle();
panneau.ajout(balle);
new Thread(new BalleSéparée(balle)).start();
}
private class BalleSéparée implements Runnable {
private Balle balle;
public BalleSéparée(Balle balle) {
this.balle = balle;
}
public void run() {
try {
while(true){
balle.déplace(panneau.getBounds());
panneau.repaint();
Thread.sleep(10);
}
}
catch (InterruptedException ex) { }
}
}
private class Panneau extends JPanel {
private ArrayList<Balle> balles = new ArrayList<Balle>();
public void ajout(Balle balle) {
balles.add(balle);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D surface = (Graphics2D) g;
g.setColor(Color.pink);
for (Balle balle : balles) surface.fill(balle.getForme());
}
}
private class Balle {
private double x, y, dx=5, dy=5;
public void déplace(Rectangle2D zone) {
x+=dx;
y+=dy;
if (x < zone.getMinX()) { x = zone.getMinX(); dx = -dx; }
if (x+15 >= zone.getMaxX()) { x = zone.getMaxX() - 15; dx = -dx; }
if (y < zone.getMinY()) { y = zone.getMinY(); dy = -dy; }
if (y+15 >= zone.getMaxY()) { y = zone.getMaxY() - 15; dy = -dy; }
}
public Ellipse2D getForme() {
return new Ellipse2D.Double(x, y, 40, 40);
}
}
public static void main(String[] args) { new ballon(); }
} |