
{filelink=10239}
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.JComponent;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AnimationConatainer extends JFrame
{
public AnimationConatainer()
{
JFrame f = new JFrame("Animation des composant en Java");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(250, 200);
f.add(new CustomContainer());
f.setVisible(true);
}
public static void main(String argv[])
{
Runnable showMyGUI = new Runnable() {
public void run() {
new AnimationConatainer();
}
};
SwingUtilities.invokeLater(showMyGUI);
}
}
class CustomContainer extends JComponent implements ActionListener {
Timer timer;
int dureeAnimation = 5000; // Le bouton reste 5 secondes dans l'ombre
long animStartTime;
int translateY = 0;
static final int MAX_Y = 100;
JButton btn;
/**
* Ajouter un composant dans le container.
* Exemple avec JButton
*
**/
public CustomContainer()
{
setLayout(new java.awt.FlowLayout());
timer = new Timer(30, this);
btn = new JButton("Démarrer l'animation");
btn.setOpaque(false);
btn.addActionListener(this);
add(btn);
}
public void paint(Graphics g) {
g.translate(0, translateY);
super.paint(g);
}
/*
* Cette méthode gère les cliques
* de lancement et d'arrêt de l'animation
*/
public void actionPerformed(ActionEvent evt) {
if (evt.getSource().equals(btn)) {
// Démarrer l'animation
if (!timer.isRunning()) {
animStartTime = System.nanoTime() / 1000000;
btn.setText("Stopper l'animation");
timer.start();
} else {
// Arrêter l'animation
timer.stop();
btn.setText("Démarrer l'animation");
translateY = 0;
repaint();
}
} else {
long currentTime = System.nanoTime() / 1000000;
long totalTime = currentTime - animStartTime;
if (totalTime > dureeAnimation) {
animStartTime = currentTime;
}
float fraction = (float)totalTime / dureeAnimation;
fraction = Math.min(1.0f, fraction);
if (fraction < .5f) {
translateY = (int)(MAX_Y * (2 * fraction));
} else {
translateY = (int)(MAX_Y * (2 * (1 - fraction)));
}
repaint();
}
}
}