package G1.particles_moving; import java.awt.Canvas; import java.awt.Graphics; import java.util.Random; import javax.swing.JApplet; /* Osnovne skracenice (shortcuts): * ctrl+space = Autocomplete - probajte cim pocnete da kucate nesto, pomaze! * ctrl+shift+F = Autoformat * ctrl+shift+O = Autoimport - svega sto nije ukljuceno, a referise se * ctrl+shift+G = Pretraga svih pojavljivanja obelezene reference * */ public class ParticleApplet extends JApplet { public ParticleApplet() { } @Override public void init() { // TODO Auto-generated method stub super.init(); setSize(500, 500); add(new ParticleCanvas(1000)); } } class ParticleCanvas extends Canvas { private Random randGen = new Random(); private Particle[] particles; public ParticleCanvas(int n) { setSize(500, 500); particles = new Particle[n]; for (int i = 0; i < n; i++) particles[i] = new Particle(randGen.nextInt(500), randGen.nextInt(500), this); // pokretanje niti, nakon cega nit pocinje da izvrsava svoj run metod for (Particle p : particles) p.start(); } @Override public void paint(Graphics g) { super.paint(g); for (Particle p : particles) { g.fillOval(p.getX(), p.getY(), 5, 5); } } } class Particle extends Thread { private int x; private int y; private ParticleCanvas canvas; public Particle(int x, int y, ParticleCanvas canvas) { super(); this.canvas=canvas; this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } private void move() { double rvx = Math.random(); double rvy = Math.random(); if (rvx < 0.33) x -= 1; else if (rvx > 0.66) x += 1; if (rvy < 0.33) y -= 1; else if (rvy > 0.66) y += 1; } @Override public void run() { while (true) { move(); try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } canvas.repaint(); } } }