IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

AWT/Swing Java Discussion :

Animation en Java


Sujet :

AWT/Swing Java

  1. #1
    Futur Membre du Club
    Femme Profil pro
    Étudiant
    Inscrit en
    Avril 2015
    Messages
    15
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Algérie

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2015
    Messages : 15
    Points : 8
    Points
    8
    Par défaut Animation en Java
    Salut tout le monde

    Je veux faire clignoter un jLabel sous netBeans. J'ai essayé le code suivat:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    public class Interface1 extends javax.swing.JFrame {
     
        /** Creates new form Interface1 */
        public Interface1() {
            initComponents(); 
     
            JLabel   lab = new logiciel.BlinkingLabel("GestOp", Color.CYAN);
     
        }
    La classe BlinkingLabel se trouve dans un package nommé " logiciel" :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
     
     
    package logiciel;
     
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
     
     
    public class BlinkingLabel extends JLabel
    {  
      Color defaultColor;   // Couleur par defaut du label
      Color blinkingColor;  // Couleur de clignotement
      Timer timer;          // Timer declenchant des tics
     
      public BlinkingLabel (String text,  Color  blinkingColor) 
      {	
        super (text);    
        this.blinkingColor = blinkingColor;
        this.defaultColor  = getForeground ();
     
        // Creation et lancement du timer
        timer = createTimer ();
        timer.start ();
      }
     
      // Methode renvoyant un timer pret a demarrer
      private Timer createTimer ()
      {
        // Creation d'une instance de listener associee au timer
        ActionListener action = new ActionListener ()
          {
            // Methode appelee a chaque tic du timer
            public void actionPerformed (ActionEvent event)
            {
              // Inversion de la couleur
              if (getForeground ().equals (defaultColor))            
                setForeground (blinkingColor);
              else
                setForeground (defaultColor);
            }
          };
     
        // Creation d'un timer qui genere un tic
        // chaque 500 millieme de seconde
        return new Timer (500, action);
      }
    Ça ne marche pas . please help

  2. #2
    Membre averti
    Avatar de omar344
    Homme Profil pro
    Développeur Java
    Inscrit en
    Juin 2007
    Messages
    287
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : Maroc

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : Enseignement

    Informations forums :
    Inscription : Juin 2007
    Messages : 287
    Points : 301
    Points
    301
    Par défaut
    Bonjour!
    Voici un exemple fonctionnel:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    import java.util.Timer;
    import java.awt.Color;
    import java.util.TimerTask;
    import javax.swing.JLabel;
     
    /**
     * A blinkable label.
     * This class adds blinking behavior to a JLabel.
     * Use setBlinking(true) to turn blinking on.
     * 
     * How it works:
     * 1. it uses a Timer and TimerTask to perform blinking.
     * 2. the TimerTask toggles the foreground color between the
     *    original foreground color and the background color.  This makes 
     *    the label text appear and disappear (when foreground == background).
     * 
     * TODO: Make this a decorator. Then you could blink any Component.
     * 
     * @author James Brucker
     */
    public class BlinkingLabel extends JLabel {
    	private static final long serialVersionUID = 1L;
    	private static final int BLINKING_RATE = 1000; // period in milliseconds
     
    	private boolean blinking = false;
    	private Timer timer = null;
     
    	/**
             * Create a new blinkable label with given text string.
             * @param text a string to display on the label.
             */
    	public BlinkingLabel(String text) {
    		super(text);	
    	}
     
    	/**
             * Turn the blinking on or off.
             * @param blinking is true to turn blinking on
             */
    	public void setBlinking(boolean blinking) {
    		if ( this.blinking == blinking ) return; // nothing to do
    		this.blinking = blinking;
    		// if there is a timer running then cancel it.
    		// there should only be a timer if the label is blinking.
    		if ( timer != null ) {
    			timer.cancel();
    			timer = null;
    		}
    		// to make the label blink, schedule a BlinkTask.
    		if ( blinking ) {
    			timer = new Timer();
    			// parameters are: (TimerTask, delay, period)
    			timer.scheduleAtFixedRate(new BlinkTask(this), 0, BLINKING_RATE);	
    		}
    	}
     
    	/**
             * Get the blinking state of the label.
             * @return true if label is in blinking state
             */
    	public boolean getBlinking( ) {
    		return this.blinking;
    	}
     
    	/**
             * A task to control blinking behavior.
             */
    	class BlinkTask extends TimerTask {
    		private JLabel label;
    		/** label's original background color */
    		private Color bg;
    		/** label's original foreground color */
    		private Color fg;
     
    		public BlinkTask(JLabel label) {
    			this.label = label;
    			fg = label.getForeground();
    			bg = label.getBackground();
    		}
     
    		/**
                     * Reverse the foreground color of label.
                     */
                    @Override
    		public void run( ) {
    			if ( label.getForeground() == fg )
    				label.setForeground(bg);
    			else label.setForeground(fg);
    		}
     
    		/**
                     * When the TimerTask is canceled, restore the original
                     * foreground color.  This ensures the label is visible.
                     */
                    @Override
    		public boolean cancel() {
    			label.setForeground(fg);
    			return true; // success
    		}
    	}
    }

  3. #3
    Futur Membre du Club
    Femme Profil pro
    Étudiant
    Inscrit en
    Avril 2015
    Messages
    15
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Algérie

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2015
    Messages : 15
    Points : 8
    Points
    8
    Par défaut
    Merci pour réponse
    J’ai essayé avec ce code main j’ai toujours le même problème. I.e. Quand je fais un appel à la classe BlinkinkLabel dans une autre class ça ne fonctionne plus :/

  4. #4
    Membre averti
    Avatar de omar344
    Homme Profil pro
    Développeur Java
    Inscrit en
    Juin 2007
    Messages
    287
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : Maroc

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : Enseignement

    Informations forums :
    Inscription : Juin 2007
    Messages : 287
    Points : 301
    Points
    301
    Par défaut
    Bonsoir!
    ce code est fonctionnel, n'oublie pas l'appel de la méthode setBlinking pour avoir le résultat souhaité

  5. #5
    Futur Membre du Club
    Femme Profil pro
    Étudiant
    Inscrit en
    Avril 2015
    Messages
    15
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Algérie

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2015
    Messages : 15
    Points : 8
    Points
    8
    Par défaut
    C'est ce que j'ai fais :/


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
     
             public Interface1() {
            initComponents(); 
            BlinkingLabel lab1 = new BlinkingLabel("GestOP");
            lab1.setBlinking(true);
            this.add(lab1);
     
     
        }

  6. #6
    Membre averti
    Avatar de omar344
    Homme Profil pro
    Développeur Java
    Inscrit en
    Juin 2007
    Messages
    287
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : Maroc

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : Enseignement

    Informations forums :
    Inscription : Juin 2007
    Messages : 287
    Points : 301
    Points
    301
    Par défaut
    En principe ca devrait marcher!

  7. #7
    Modérateur
    Avatar de joel.drigo
    Homme Profil pro
    Ingénieur R&D - Développeur Java
    Inscrit en
    Septembre 2009
    Messages
    12 430
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 54
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Ingénieur R&D - Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Septembre 2009
    Messages : 12 430
    Points : 29 131
    Points
    29 131
    Billets dans le blog
    2
    Par défaut
    Salut,

    Quand tu dis que "ça ne marche pas", qu'est-ce qu'il se passe et qu'est-ce qu'il ne se passe pas ? Le label s'affiche t-il au moins ?

    Sinon, voir un autre exemple ici. Vois-tu les lignes clignoter quand tu le testes ?
    L'expression "ça marche pas" ne veut rien dire. Indiquez l'erreur, et/ou les comportements attendus et obtenus, et donnez un Exemple Complet Minimal qui permet de reproduire le problème.
    La plupart des réponses à vos questions sont déjà dans les FAQs ou les Tutoriels, ou peut-être dans une autre discussion : utilisez la recherche interne.
    Des questions sur Java : consultez le Forum Java. Des questions sur l'EDI Eclipse ou la plateforme Eclipse RCP : consultez le Forum Eclipse.
    Une question correctement posée et rédigée et vous aurez plus de chances de réponses adaptées et rapides.
    N'oubliez pas de mettre vos extraits de code entre balises CODE (Voir Mode d'emploi de l'éditeur de messages).
    Nouveau sur le forum ? Consultez Les Règles du Club.

  8. #8
    Futur Membre du Club
    Femme Profil pro
    Étudiant
    Inscrit en
    Avril 2015
    Messages
    15
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Algérie

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2015
    Messages : 15
    Points : 8
    Points
    8
    Par défaut
    Bonjour,
    Lorsque j’ajoute une class main dans la class BlinkingLAbel (pour tester) j’ai le résultat souhaité.
    Mais, quand j’appelle la class BlinkingLAbel dans une autre interface le Label ne s’affiche même pas
    PS : j’ai essayé d’utiliser un Label qui est déjà dans l'interface (je travaille sous netBeans) mais j’ai toujours pas de résultat.

  9. #9
    Modérateur
    Avatar de joel.drigo
    Homme Profil pro
    Ingénieur R&D - Développeur Java
    Inscrit en
    Septembre 2009
    Messages
    12 430
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 54
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Ingénieur R&D - Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Septembre 2009
    Messages : 12 430
    Points : 29 131
    Points
    29 131
    Billets dans le blog
    2
    Par défaut
    Je suppose que c'est un JLabel créé dans la palette : évidemment, il faut remplacer la classe standard utilisée par la palette de NetBeans par le BlinkingLabel.

    Ou faire un wrapper :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    109
    110
    111
    112
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Timer;
    import java.util.TimerTask;
     
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
     
    public class BlinkingComponent {
     
    	private final JComponent component;
    	private final Timer timer;
    	private BlinkingTask timerTask; 
     
    	public BlinkingComponent(JComponent component) {
    		this.component = component;
    		this.timer = new Timer();
    	}
     
    	public final void start(final long period) {
    		start(null, period);
    	}
     
    	public final void start(final Color blinkingColor, final long period) {
    		start(blinkingColor, component.getForeground(), period);
    	}
     
    	public final synchronized void start(final Color blinkingColor,
    			final Color color, final long period) {
    		if (timerTask != null) {
    			stop();
    		}
    		timerTask = new BlinkingTask(blinkingColor, color);
    		timer.scheduleAtFixedRate(timerTask, period, period);
    	}
     
    	public final synchronized boolean isBlinking() {
    		return timerTask != null;
    	}
     
    	public final synchronized void stop() {
    		if (timerTask != null) {
    			timerTask.cancel();
    			component.setForeground(timerTask.foregroundColor);
    			timerTask = null;
    		}
    	}
     
    	private class BlinkingTask extends TimerTask {
    		public final Color foregroundColor;
    		public final Color blinkingColor;
     
    		private boolean blink;
     
    		public BlinkingTask(Color blinkingColor, Color color) {
    			this.foregroundColor = color == null ? component.getForeground() : color;
    			this.blinkingColor = blinkingColor;
    		}
     
    		@Override
    		public void run() {
    			if (blink) {
    				component.setForeground(foregroundColor);
    			} else if (blinkingColor == null) {
    				component.setForeground(component.getBackground());
    			} else {
    				component.setForeground(blinkingColor);
    			}
    			blink = !blink;
    		}
    	}
     
    	public static void main(String[] args) {
    		JFrame frame = new JFrame("Démo");
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
    		JLabel label = new JLabel("Hello!", JLabel.CENTER);
     
    		final JButton button = new JButton("Stop");
     
    		frame.add(label);
    		frame.add(button, BorderLayout.SOUTH);
    		frame.setSize(300, 200);
    		frame.setLocationRelativeTo(null);
    		frame.setVisible(true);
     
    		BlinkingComponent blinkComponent = new BlinkingComponent(label); // si label est le label que tu as dans ton interface ça fonctionnera
    		button.addActionListener(new ActionListener() {
     
    			boolean blink = true;
     
    			@Override
    			public void actionPerformed(ActionEvent e) {
    				if (blink) {
    					blinkComponent.stop();
    					button.setText("Start");
    				} else {
    					blinkComponent.start(Color.RED, 500);
    					button.setText("Stop");
    				}
    				blink = !blink;
    			}
    		});
    		blinkComponent.start(500); // période = 500 ms
     
    	}
     
    }
    L'expression "ça marche pas" ne veut rien dire. Indiquez l'erreur, et/ou les comportements attendus et obtenus, et donnez un Exemple Complet Minimal qui permet de reproduire le problème.
    La plupart des réponses à vos questions sont déjà dans les FAQs ou les Tutoriels, ou peut-être dans une autre discussion : utilisez la recherche interne.
    Des questions sur Java : consultez le Forum Java. Des questions sur l'EDI Eclipse ou la plateforme Eclipse RCP : consultez le Forum Eclipse.
    Une question correctement posée et rédigée et vous aurez plus de chances de réponses adaptées et rapides.
    N'oubliez pas de mettre vos extraits de code entre balises CODE (Voir Mode d'emploi de l'éditeur de messages).
    Nouveau sur le forum ? Consultez Les Règles du Club.

  10. #10
    Futur Membre du Club
    Femme Profil pro
    Étudiant
    Inscrit en
    Avril 2015
    Messages
    15
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Algérie

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2015
    Messages : 15
    Points : 8
    Points
    8
    Par défaut
    Bonsoir,
    Le problème n'est toujours pas résolu, Je n’arrive pas à comprendre pourquoi

  11. #11
    Membre averti
    Avatar de omar344
    Homme Profil pro
    Développeur Java
    Inscrit en
    Juin 2007
    Messages
    287
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : Maroc

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : Enseignement

    Informations forums :
    Inscription : Juin 2007
    Messages : 287
    Points : 301
    Points
    301
    Par défaut
    est ce que tu peux poster tout ton code?

  12. #12
    Futur Membre du Club
    Femme Profil pro
    Étudiant
    Inscrit en
    Avril 2015
    Messages
    15
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Algérie

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2015
    Messages : 15
    Points : 8
    Points
    8
    Par défaut
    Ça marche enfin avec un tout petit arrangement au ceint du constructeur comme suit:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    JLabel l;
     
    	public Blinking(JLabel text) {
    		this.l = text;
    	}
    Un appel de la class Blinking de la manière suivante m'a permis d'avoir le résultat souhaité
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
     Blinking b = new Blinking(lab);
            b.setBlinking(true);
    Thanks for all

  13. #13
    Membre averti
    Avatar de omar344
    Homme Profil pro
    Développeur Java
    Inscrit en
    Juin 2007
    Messages
    287
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : Maroc

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : Enseignement

    Informations forums :
    Inscription : Juin 2007
    Messages : 287
    Points : 301
    Points
    301
    Par défaut
    un clic sur le bouton serait le bienvenue

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Animation en java
    Par Mo_Poly dans le forum 2D
    Réponses: 5
    Dernier message: 01/03/2007, 18h04
  2. Animation sous Java
    Par f2001 dans le forum Applets
    Réponses: 13
    Dernier message: 19/08/2006, 19h05
  3. animation en java
    Par mwanjany dans le forum Langage
    Réponses: 3
    Dernier message: 10/04/2006, 13h20
  4. Afficher un gif animé en Java
    Par julio26 dans le forum 2D
    Réponses: 5
    Dernier message: 06/03/2006, 12h04
  5. [Stratégie]Boucle d'animation en Java
    Par Invité dans le forum Graphisme
    Réponses: 10
    Dernier message: 01/02/2005, 19h49

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo