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 :

Message defilant plus fluide


Sujet :

AWT/Swing Java

  1. #1
    Membre à l'essai
    Profil pro
    Inscrit en
    Avril 2003
    Messages
    42
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2003
    Messages : 42
    Points : 24
    Points
    24
    Par défaut Message defilant plus fluide
    Bonjour,

    J'utilise ce bout de programme dans un timer pour faire défiler un message dans une jtextfield, le souci c'est que le défilement n'est pas fluide voir saccadé, est-ce à cause de la taille du message qui est diffusé avec une police importante compte tenu des besoins ou y a-t-il une autre solution ?

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    public void displayMessage(){
    			char c = this.message.charAt(0);
    			msg = this.message.substring(1);
    			this.message = msg + c;
    			this.jtextMessage.setText(this.message);			
    		}
    merci

  2. #2
    Rédacteur/Modérateur

    Avatar de bouye
    Homme Profil pro
    Information Technologies Specialist (Scientific Computing)
    Inscrit en
    Août 2005
    Messages
    6 840
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 47
    Localisation : Nouvelle-Calédonie

    Informations professionnelles :
    Activité : Information Technologies Specialist (Scientific Computing)
    Secteur : Agroalimentaire - Agriculture

    Informations forums :
    Inscription : Août 2005
    Messages : 6 840
    Points : 22 854
    Points
    22 854
    Billets dans le blog
    51
    Par défaut
    Ou vois-tu un défilement ? Ici tu changes le texte en supprimant un caractère a la fois, il est donc tout a fait normal que ca "saccade" et effectivement encore plus quand la police est grande.

    Ce n'est pas comme cela qu'on fait défiler du texte. Go surcharger paintComponent() et dessiner le texte à un instant t à une position en pixel donnée !
    Merci de penser au tag quand une réponse a été apportée à votre question. Aucune réponse ne sera donnée à des messages privés portant sur des questions d'ordre technique. Les forums sont là pour que vous y postiez publiquement vos problèmes.

    suivez mon blog sur Développez.

    Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the universe trying to produce bigger and better idiots. So far, the universe is winning. ~ Rich Cook

  3. #3
    Membre à l'essai
    Profil pro
    Inscrit en
    Avril 2003
    Messages
    42
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2003
    Messages : 42
    Points : 24
    Points
    24
    Par défaut
    Salut,

    Je pensais bien que je ne pouvais pas y échapper, je te remercie de la confirmation, connais-tu un code correspondant déjà existant ?

    merci encore

    mo

  4. #4
    Membre à l'essai
    Profil pro
    Inscrit en
    Avril 2003
    Messages
    42
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2003
    Messages : 42
    Points : 24
    Points
    24
    Par défaut
    Re, en utilisant le code ci-dessous, le résultat n'est pas meilleur, qqchose m'échappe !

    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
    /**
             * Permet de modifier la position du texte dans le label suivant le temps
             * écoulé.
             */
    	public void paintComponent(Graphics g) {
    		if (isOpaque()) {
    			g.setColor(getBackground());
    			g.fillRect(0, 0, getWidth(), getHeight());
    		}
    		g.setColor(getForeground());
     
    		FontMetrics fm = g.getFontMetrics();
    		Insets insets = getInsets();
     
    		int width = getWidth() - (insets.left + insets.right);
    		int height = getHeight() - (insets.top + insets.bottom);
     
    		int textWidth = fm.stringWidth(getText());
     
    		if (width < textWidth) {
    			width = textWidth + offset;
    		}
     
    		x %= width;
     
    		int textX = insets.left + x;
    		int textY = insets.top + (height - fm.getHeight()) / 2  + fm.getAscent() ;
     
    		g.drawString(getText(), textX, textY);
    		g.drawString(getText(), textX + (speed > 0 ? -width : width), textY+2);
    	}
     
    	/**
             * On définit dans cette méthode une tache que l'on va ordonnancer suivant un
             * Timer.
             */
    	public void start() {
    		Timer timer = new Timer();
    		TimerTask task = new TimerTask() {
    			public void run() {
    				x += speed;
    				repaint();
    			}
    		};
    		timer.scheduleAtFixedRate(task, 0, period);
    	}

  5. #5
    Expert éminent sénior
    Avatar de sinok
    Profil pro
    Inscrit en
    Août 2004
    Messages
    8 765
    Détails du profil
    Informations personnelles :
    Âge : 43
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Août 2004
    Messages : 8 765
    Points : 12 977
    Points
    12 977
    Par défaut
    Deux choses,

    1 Quelle période et delta utilises tu?
    2 Utilises de préférence un timer Swing (javax.swing.TImer) qui lui est prévu pour fonctionner correctement avec l'EDT, au contraire du combo Time+TimerTask
    3 Pour des animations fluides, il est préférable de calculer la position en fonction du temps passé depuis le démarrage de l'animation, et non faire une simple incrémentation qui est dépendant du temps d'exécution du timer.
    Hey, this is mine. That's mine. All this is mine. I'm claiming all this as mine. Except that bit. I don't want that bit. But all the rest of this is mine. Hey, this has been a really good day. I've eaten five times, I've slept six times, and I've made a lot of things mine. Tomorrow, I'm gonna see if I can't have sex with something.

  6. #6
    Membre à l'essai
    Profil pro
    Inscrit en
    Avril 2003
    Messages
    42
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2003
    Messages : 42
    Points : 24
    Points
    24
    Par défaut
    Un bout de code pour illustrer ton propos me permettrait d'y voir plus clair !

  7. #7
    Expert éminent sénior
    Avatar de sinok
    Profil pro
    Inscrit en
    Août 2004
    Messages
    8 765
    Détails du profil
    Informations personnelles :
    Âge : 43
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Août 2004
    Messages : 8 765
    Points : 12 977
    Points
    12 977
    Par défaut
    En mode à l'arrache et un peu naïf, un truc comme ça:

    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
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    package fr.sca.tests;
     
     
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.geom.Point2D;
     
     
    /**
     * Created by sinok on 28/02/15.
     */
    public class AnimatedText extends JPanel {
     
     
        private int period = 20;
        private float movementByMillisecond = 0.15f;
        private String text = "Hello World!";
        private long lastExec = 0;
        private Point2D.Float location = new Point2D.Float(150, 20);
        private Timer timer = new Timer(period, new ActionListener() {
     
     
            @Override
            public void actionPerformed(ActionEvent e) {
                AnimatedText.this.repaint();
                System.out.println("Timer tick");
            }
     
     
        });
     
     
        public static void main(String[] args) {
            JFrame f = new JFrame("Exemple");
            final AnimatedText t = new AnimatedText();
            JButton start = new JButton("Start");
            start.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    t.startAnimation();
                }
            });
     
     
            JButton stop = new JButton("Stop");
            stop.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    t.stopAnimation();
                }
            });
     
     
            JButton reset = new JButton("Reset");
            reset.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    t.reset();
                }
            });
     
     
            JPanel p = new JPanel();
            p.add(start);
            p.add(stop);
            p.add(reset);
     
     
            f.add(t, BorderLayout.CENTER);
            f.add(p, BorderLayout.SOUTH);
            f.setSize(800, 600);
            f.setLocationRelativeTo(null);
            f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
     
     
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (UnsupportedLookAndFeelException e) {
                e.printStackTrace();
            }
     
     
            f.setVisible(true);
        }
     
     
        private Point2D.Float computePositionFromTime(Point2D.Float previousLocation, long millisecondsElapsed) {
            float movement = millisecondsElapsed * movementByMillisecond;
            Point2D.Float location = new Point2D.Float(previousLocation.x, previousLocation.y + movement);
            return location;
        }
     
     
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (lastExec == 0) {
                location = computePositionFromTime(location, 0);
            } else {
                location = computePositionFromTime(location, System.currentTimeMillis() - lastExec);
            }
            lastExec = System.currentTimeMillis();
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.drawString(text, location.x, location.y);
     
     
        }
     
     
        public void startAnimation() {
            timer.start();
        }
     
     
        public void stopAnimation() {
            timer.stop();
            System.out.println("Stopping timer");
        }
     
     
        public void reset() {
            location = new Point2D.Float(150, 20);
            lastExec = 0;
        }
    }
    Hey, this is mine. That's mine. All this is mine. I'm claiming all this as mine. Except that bit. I don't want that bit. But all the rest of this is mine. Hey, this has been a really good day. I've eaten five times, I've slept six times, and I've made a lot of things mine. Tomorrow, I'm gonna see if I can't have sex with something.

  8. #8
    Membre à l'essai
    Profil pro
    Inscrit en
    Avril 2003
    Messages
    42
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2003
    Messages : 42
    Points : 24
    Points
    24
    Par défaut
    Merci mais laisse moi le temps de comprendre ... J'ai trouvé un autre code donc j'essaye d'y voir clair
    Images attachées Images attachées  

  9. #9
    Membre à l'essai
    Profil pro
    Inscrit en
    Avril 2003
    Messages
    42
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2003
    Messages : 42
    Points : 24
    Points
    24
    Par défaut
    J'ai fait ça qui marche plutôt bien même si je ne suis pas convaincu sur tout :

    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
     
    @Override public void run() {
    	     while (processus != null) {
    	      repaint();
    	      x_coord--;
    	      if (x_coord <= -(len)) 
    	    	  	x_coord = getSize().width;
    		      try {
    		        Thread.sleep(speed);
    		      } catch (InterruptedException e){}
    	     }
          processus = null;
        }
     
        @Override public void paintComponent(Graphics gi) {
            if (len == 0) {  
            	 int w = getSize().width;	
            	 int h = getSize().height;	
            	 Image img = createImage(w,h);		// au premier appel, on crée une image qui sera de la taille du panel
    	         gi = img.getGraphics();			// on récupère l'objet Graphics
    	         FontMetrics fm = gi.getFontMetrics();	// puis on a accès aux données sur la police
    	         len = fm.stringWidth(msg) * 7;		// on initialise la largeur du message * 7 à revoir [passage complet du message]
    	         x_coord = getSize().width;			// x = largeur du panel
    	         y_coord = (getSize().height-fm.getHeight())/2+fm.getAscent();	// y = hauteur du panel - hauteur de police / 2 + ajustement
            } 
            gi.setColor(getBackground());
            gi.fillRect(0,0,getSize().width,getSize().height);
            gi.setColor(getForeground());
            gi.drawString(msg, x_coord, y_coord);
        }

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

Discussions similaires

  1. Utilisation de la cache HTTP = plus fluide
    Par victorb dans le forum IGN API Géoportail
    Réponses: 1
    Dernier message: 18/12/2012, 14h19
  2. Rendre une animation (sliders) plus fluide
    Par boutmos dans le forum Général JavaScript
    Réponses: 9
    Dernier message: 11/05/2009, 11h38
  3. Paramètrage de swfobject pour une lecture plus fluide
    Par Malola dans le forum Intégration
    Réponses: 0
    Dernier message: 25/11/2008, 11h25
  4. Réponses: 6
    Dernier message: 19/10/2007, 17h00
  5. Emetteurs n'ayant pas envoyé de message depuis plus d'1 an
    Par emccbo dans le forum Requêtes et SQL.
    Réponses: 2
    Dernier message: 23/08/2007, 14h36

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