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
| import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Fenetre3 extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
private Pananimation pan2 = new Pananimation();
private JButton btnnext2 = new JButton("mon bouton");
private JPanel container2 = new JPanel();
public Fenetre3(){
this.setTitle("Animation");
this.setSize(300, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
container2.setBackground(Color.white);
container2.setLayout(new BorderLayout());
container2.add(pan2, BorderLayout.CENTER);
container2.add(btnnext2, BorderLayout.SOUTH);
this.setContentPane(container2);
this.setVisible(true);
go();
}
private void go(){
//Les coordonnées de départ de notre rond
int x = pan2.getX(), y = pan2.getY();
//Le booléen pour savoir si l'on recule ou non sur l'axe x
boolean backX = false;
//Le booléen pour savoir si l'on recule ou non sur l'axe y
boolean backY = false;
//Dans cet exemple, j'utilise une boucle while
//Vous verrez qu'elle fonctionne très bien
while(true){
//Si la coordonnée x est inférieure à 1, on avance
if(x < 1)backX = false;
//Si la coordonnée x est supérieure à la taille du Panneau moins la taille du rond, on recule
if(x > pan2.getWidth()-50)backX = true;
//Idem pour l'axe y
if(y < 1)backY = false;
if(y > pan2.getHeight()-50)backY = true;
//Si on avance, on incrémente la coordonnée
if(!backX)
pan2.setPosX(++x);
//Sinon, on décrémente
else
pan2.setPosX(--x);
//Idem pour l'axe Y
if(!backY)
pan2.setPosY(++y);
else
pan2.setPosY(--y);
//On redessine notre Panneau
pan2.repaint();
//Comme on dit : la pause s'impose ! Ici, trois millièmes de seconde
try {
Thread.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} |