You are on page 1of 2

Class Anima - datos

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

1/2

/* Por: Ing. Edwin Fredy Mamani Calderon */


/* Curso: Metodologa de la Programacin */
/* Practica: Animacion
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Anima extends JFrame implements Runnable,ActionListener {
//declarando variables objetos
private Thread hilo;
private JButton bot;
private JButton bstop;
private boolean stop;
private boolean pause;
private Point d;
private int lad;
//constructor
Anima() {
super("ThreadDemo");
setLayout(null);
//creando hilo
hilo = new Thread(this);
//creadno objetos botones
bot = new JButton("||");
bstop = new JButton("Stop");
//creando punto para guardar direcciones
d = new Point(1,1);
//lado del cuadrado
lad = 50;
//variable para parar hilo y para pausarlo
stop = false;
pause = false;
//ubicando objetos
bot.setBounds(0,0,lad,lad);
bot.addActionListener(this);
bstop.setBounds(100,0,lad*2,lad);
bstop.addActionListener(this);
//agregando al jframe los botones
add(bot);
add(bstop);
//inicializando hilo
hilo.start();
}
//ActionPerformed para recivir eventos de botones con prefijo "synchr
onized"
//Para interactuar con run
public synchronized void actionPerformed(ActionEvent e){
String str = ((JButton)e.getSource()).getText();
//Para pausar y resumir
if(str.equals("||")){
22/12/2013 09:58:43 AM

Class Anima - datos (continuado)

2/2

bot.setText(">");
pause = true;
}else if(str.equals(">")){
pause = false;
notify();
bot.setText("||");
}
//Parar hilo
if(str.equals("Stop")){
stop = true;
bstop.setEnabled(false);
bot.setEnabled(false);
}

49
50
51
52
53
54
55
56
57
58
59
60
61

}
public void run() {
//atrapador de excepciones
try{
while(!stop){
Thread.sleep(10);
//if(hilo==Thread.currentThread()){
//almacenamos en p la posicion del bot
Point p = bot.getLocation();
Dimension dim = this.getContentPane().getSize();
//cambiar valor de posicion de acuerdo a la direcci

62
63
64
65
66
67
68
69
70
71
72

n
p.x += d.x;
p.y += d.y;
//si posicion del objeto llega a los limites cambiar

73
74
75

direccion
if(p.x+lad>dim.width)d.x=-1;
if(p.y+lad>dim.height)d.y=-1;
if(p.x<0)d.x = 1;
if(p.y<0)d.y = 1;
//mover objeto
bot.setLocation(p.x,p.y);
//si el boton pause wait()
synchronized(this) { if(pause)wait(); }

76
77
78
79
80
81
82
83

//}
}
}catch(InterruptedException e){ }

84
85
86

}
public static void main () {
Anima t = new Anima();
t.setBounds(0,0,500,500);
t.setVisible(true);
}

87
88
89
90
91
92
93

22/12/2013 09:58:43 AM

You might also like