Applet Java : Un cercle qui se déplace
Bonjour :)
j'ai un TP en Java qui consiste à écrire une applet qui affiche un cercle qui se déplace avec une vitesse donnée pour entrer dans une barriére (Rectangle): Utilisation de 2 Buttons : Start & Stop
A votre avis est il possible de travailler qu'avec la méthode :
Code:
public boolean action
sans se sérvir des Interfaces Listner ?
Voici quelques problémes que j'ai rencontré :
-Quand je clique sur commencer mon thread n'agit pas .
-Je ne sais pas comment récupérer la vitesse entrée dans mon TextField.
Voici mon code : Applet.java
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 103 104 105 106 107 108
| import java.applet.*;
import java.awt.*;
import java.awt.color.*;
import java.awt.event.*;
public class cercle extends Applet implements Runnable
{
Thread th;
int x =0;
int i=0;
TextField t1;
public void init()
{
Panel p =new Panel();
setLayout(new GridLayout(3,1));
Button a2 = new Button("Commencer");
Button a1= new Button("Arréter");
t1= new TextField(8);
Label t = new Label("Vitesse");
TextField t22= new TextField(8);
Label t13 = new Label("temps");
p.add(a2);
p.add(a1);
p.add(t);
p.add(t1);
p.add(t13);
p.add(t22);
setLayout(new BorderLayout());
add("South",p);
}
public void start()
{
th=new Thread(this);
th.start();
}
public void run(){
int k=0;
for(int i = -50; i < 600; i++)
{int x= getPosX();
x++;
setPosX(x);
repaint();
try{
th.sleep(20);
}
catch(InterruptedException e){}}}
public void stop(){
th.stop();
}
private int posX = 0;
private int posY = 0;
public void paint(Graphics g){
g.drawRect(310, 20, 90, 90);
g.setColor(Color.red);
g.fillOval(posX, 36, 50, 50);
}
public int getPosX() {
return posX;
}
public void setPosX(int posX) {
this.posX = posX;
}
public boolean action(Event e, Object arg){
if(arg=="Commencer")
{ th.start();
}
if(arg=="Arréter")
{th.stop();
}
return true;
}
} |
Merci beaucoup pour votre aide :)