Mese: Ottobre 2014
JLaser
public class JLaser extends JPanel implements Runnable { public JLaser() { this.setSize(1, 10); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.YELLOW); g.drawLine(0, 0, 0, 9); } public void fire() { Thread thread = new Thread(this); thread.setDaemon(true); thread.start(); } @Override public void run() { while (this.getY() >= 0) { this.setLocation(this.getX(), this.getY() - 10); try { Thread.sleep(20); } catch (InterruptedException ex) { } } setVisible(false); this.getParent().remove(this); } }
Codice da utilizzare nel Main:
@Override public void mouseMoved(MouseEvent me) { pnlAstronave.setLocation(me.getX()-5, pnlAstronave.getY()); } @Override public void keyReleased(KeyEvent ke) { if (ke.getKeyChar()==' ') { JLaser laser = new JLaser(); laser.setBounds(pnlAstronave.getX()+5, pnlAstronave.getY()-10, 1, 10); panel.add(laser); laser.setVisible(true); laser.fire(); } }
Agitazione termica
public class H2O extends JComponent implements Runnable { private int dx = 0, dy = 0; public H2O() { this.setPreferredSize(new Dimension(100, 100)); Thread thread = new Thread(this); thread.setDaemon(true); thread.start(); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.BLUE); g.fillOval(60 + dx, 50 + dy, 10, 10); g.fillOval(50 + dx, 60 + dy, 10, 10); g.setColor(Color.RED); g.fillOval(45 + dx, 45 + dy, 20, 20); } @Override public void run() { while (true) { dx = (int) (Math.random() * 20 - 10); dy = (int) (Math.random() * 20 - 10); repaint(); try { Thread.sleep(50); } catch (InterruptedException ex) { } } } }
Esercizio sui thread per la 5E
Realizzare un’applicazione visuale che utilizzando la classe Swing JProgressBar (vedere la documentazione on-line o sul libro di testo) simuli il caricamento di una pagina web. Realizzare un thread che in un tempo di 10 secondi faccia avanzare la progress bar da 0% a 100%. Il ciclo nel metodo run del thread deve aggiornare la barra ogni decimo di secondo. Il thread deve avviarsi alla pressione di un pulsante Carica.
Esempio realizzato in classe sui thread: EsempioThread.zip