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 :

[Stratégie] JButton animés


Sujet :

AWT/Swing Java

  1. #1
    Membre à l'essai
    Profil pro
    Inscrit en
    Juin 2007
    Messages
    53
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2007
    Messages : 53
    Points : 18
    Points
    18
    Par défaut [Stratégie] JButton animés
    Bonjour,

    Est-il possible, lorsque l'on passe la souris sur un JButton (ou une classe en dérivant), de générer une petite animation pendant laquelle le bouton s'agrandit ?
    Actuellement, j'ai ajouté un handler, et lorsque la souris passe, je ne fais que changer la taille de mon bouton, mais ce n'est pas très joli...

    Thomas

  2. #2
    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
    Pour faire un Dock à la mac tu peux oublier les JButton....


    Va falloir créer ton composant perso héritant de JComponent et aller mettre les mains dans java2d.
    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.

  3. #3
    Membre à l'essai
    Profil pro
    Inscrit en
    Juin 2007
    Messages
    53
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2007
    Messages : 53
    Points : 18
    Points
    18
    Par défaut
    Une autre idée peut-être dans ce cas ?
    C'est vraiment le style dock à la MAC qu'il me faut ... vous pensez que c'est impossible en Java ?

    T.

  4. #4
    Membre à l'essai
    Profil pro
    Inscrit en
    Juin 2007
    Messages
    53
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2007
    Messages : 53
    Points : 18
    Points
    18
    Par défaut
    Oups pardon .. j'avais pas vu la dernière phrase
    La question que je me pose, c'est : est-il possible de faire ce genre de fondus justement avec Java2D...?

    T.

  5. #5
    Membre à l'essai
    Profil pro
    Inscrit en
    Juin 2007
    Messages
    53
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2007
    Messages : 53
    Points : 18
    Points
    18
    Par défaut
    Bonjour,

    J'ai réussi à mettre en place mes boutons animés, en étendant la classe JComponent (merci sinok !) et en utilisant un petit timer de rien du tout pour la durée de mon animation.
    Mon problème est le suivant :
    Lorsque je place mes boutons dans une petite fenêtre, tout est bien fluide...
    mais quand j'agrandis cette dernière, ça devient littéralement épouvantable niveau lenteur !

    Quelqu'un a une idée du pourquoi ... et mieux encore ... une petite idée du comment résoudre ce problème ?

    Merci.
    Thomas

  6. #6
    Modérateur
    Avatar de dinobogan
    Homme Profil pro
    ingénieur
    Inscrit en
    Juin 2007
    Messages
    4 073
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France

    Informations professionnelles :
    Activité : ingénieur
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juin 2007
    Messages : 4 073
    Points : 7 163
    Points
    7 163
    Par défaut
    Citation Envoyé par anaxa_gore Voir le message
    Bonjour,

    J'ai réussi à mettre en place mes boutons animés, en étendant la classe JComponent (merci sinok !) et en utilisant un petit timer de rien du tout pour la durée de mon animation.
    Mon problème est le suivant :
    Lorsque je place mes boutons dans une petite fenêtre, tout est bien fluide...
    mais quand j'agrandis cette dernière, ça devient littéralement épouvantable niveau lenteur !

    Quelqu'un a une idée du pourquoi ... et mieux encore ... une petite idée du comment résoudre ce problème ?

    Merci.
    Thomas
    Cela vient de ton algo. Sans le code, impossible de t'aider
    N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java
    Que la force de la puissance soit avec le courage de ta sagesse.

  7. #7
    Membre à l'essai
    Profil pro
    Inscrit en
    Juin 2007
    Messages
    53
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2007
    Messages : 53
    Points : 18
    Points
    18
    Par défaut
    voilà le code !

    Le bouton animé :
    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
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
     
    public class MSS_Button extends JComponent implements Runnable {
    	public static final long serialVersionUID = 1;
     
    	/** The initial size of a button. */
    	public static final int BUTTON_INIT_SIZE = 60;
    	/** The final size of a button. */
    	public static final int BUTTON_FINAL_SIZE = 80;
     
    	/** The actual size of button. */
    	public int size = 60;
     
    	/** The thread to zoom in. */
    	private Thread zoomIn = null;
    	/** The thread to zoom out. */
    	private Thread zoomOut = null;
    	/** A boolean which says if we are zooming in. */
    	private boolean isZoomIn = false;
    	/** A boolean which says if we are zooming out. */
    	private boolean isZoomOut = false;
     
    	/** The button picture url. */
    	private ImageIcon icon = null;
     
    	/** The transparency of picture to display. */
    	private float transparency = 0.4f; 
     
     
    	/**
             * 
             */
    	public MSS_Button(URL picture) {
    		super();
    		icon = new ImageIcon(picture);
    		this.setOpaque(false);
    		this.setSize(BUTTON_INIT_SIZE, BUTTON_INIT_SIZE);
    		this.setPreferredSize(new Dimension(BUTTON_INIT_SIZE, BUTTON_INIT_SIZE));
    		this.addMouseListener(new MSS_Button_MouseListener());
    	}
     
    	/**
             * Starts the thread to zoom in.
             */
    	public void startZoomIn()
    	{
    		isZoomIn = true;
    		zoomIn = new Thread(this);
    		zoomIn.start();
    	}
    	/**
             * Stop the thread to zoom in.
             */
    	public void stopZoomIn()
    	{
    		isZoomIn = false;
    	}
    	/**
             * Starts the thread to zoom out.
             */
    	public void startZoomOut()
    	{
    		isZoomOut = true;
    		zoomOut = new Thread(this);
    		zoomOut.start();
    	}
    	/**
             * Stop the thread to zoom out.
             */
    	public void stopZoomOut()
    	{
    		isZoomOut = false;
    	}
     
    	public void setTransparency(float trans)
    	{
    		transparency = trans;
    	}
     
     
     
    	@Override
    	public void update(Graphics g) {
    		paint(g);
    	}
     
    	@Override
    	public void paint(Graphics g) {
    		super.paint(g);
    		Graphics2D g2d = (Graphics2D)g;
    		g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,transparency));
    		g2d.drawImage(icon.getImage(),0,0,getWidth(),getHeight(),null);
    		g2d.dispose();
    	}
     
    	@Override
    	public void run() {
    		while(size <= 80 && isZoomIn)
    		{
    			repaint();
    			size = size+2;
    			this.setSize(new Dimension(size,size));
    			try {
    				Thread.sleep(10);
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    		}
     
    		while(size >= 60 && isZoomOut)
    		{
    			repaint();
    			size = size-2;
    			this.setSize(new Dimension(size,size));
    			try {
    				Thread.sleep(10);
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    		}
    	}
     
    	/**
             * This class implements the graphical behaviour of an MSS_ActionButton
             * @author Thomas Bonavia
             *
             * @see MouseListener.
             * @see MSS_ActionButton.
             */
    	private class MSS_Button_MouseListener implements MouseListener
    	{	
    		/**
                     * When the mouse first button is pressed on the {@code MSS_ActionButton},
                     * The icon becomes opaque.
                     * @param       arg0    The mouse event.
                     */
    		@Override
    		public void mousePressed(MouseEvent arg0) {
    			MSS_Button b = (MSS_Button)arg0.getSource();
    			if(arg0.getButton() == MouseEvent.BUTTON1)
    			{
    				b.setTransparency(1.0f);
    			}
    				b.repaint();
    		}
     
    		/**
                     * When the mouse first button is release on the {@code MSS_ActionButton},
                     * The icon becomes semi-transparent (like in {@code MouseEntered}).
                     * @param       arg0    The mouse event.
                     */
    		@Override
    		public void mouseReleased(MouseEvent arg0) {
    			MSS_Button b = (MSS_Button)arg0.getSource();
    			if(arg0.getButton() == MouseEvent.BUTTON1)
    			{
    				b.setTransparency(0.7f);
    			}
    			b.repaint();
    		}
     
    		/**
                     * When the mouse enter on the {@code MSS_ActionButton},
                     * The icon becomes semi-transparent.
                     * @param       arg0    The mouse event.
                     */
    		@Override
    		public void mouseEntered(MouseEvent arg0) {
    			MSS_Button b = (MSS_Button)arg0.getSource();
    			b.setTransparency(0.7f);
    			b.stopZoomOut();
    			b.startZoomIn();
    		}
     
    		/**
                     * When the mouse exit the {@code MSS_ActionButton},
                     * The icon becomes more transparent.
                     * @param       arg0    The mouse event.
                     */
    		@Override
    		public void mouseExited(MouseEvent arg0) {
    			MSS_Button b = (MSS_Button)arg0.getSource();
    			b.setTransparency(0.4f);
    			b.stopZoomIn();
    			b.startZoomOut();
    		}
     
    		@Override
    		public void mouseClicked(MouseEvent arg0) {}
    	}
     
    }
    Quand je ne mets que les boutons directement dans la fenêtre, ça reste A PEU PRES fluide. Mais quand je rajoute la barre qui doit contenir les boutons alors là ...!

    Voil le code de la barre :
    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
     
    public class MSS_ButtonBar extends JComponent {
    public static final long serialVersionUID = 1;
     
    	/** The bar has a vertical orientation */
    	public static final int VERTICAL = 1;
    	/** The bar has an horizontal orientation */
    	public static final int HORIZONTAL = 2;
     
    	private int orientation;
     
    	/**
             * Constructor.
             * This constructor creates a button bar with size adapted to
             * the number of buttons the user wants to include in.
             * 
             * @param nb_buttons    The initial number of {@code MSS_Button}s.
             */
    	public MSS_ButtonBar(int nb_buttons, int orientation)
    	{
    		super();
    		int width = 0;
    		int height = 0;
     
    		if(orientation == HORIZONTAL)
    		{
    			width = nb_buttons*MSS_Button.BUTTON_INIT_SIZE + 7*nb_buttons;
    			height = MSS_Button.BUTTON_FINAL_SIZE + 10;
    		}
    		else if(orientation == VERTICAL)
    		{
    			width = MSS_Button.BUTTON_FINAL_SIZE + 10;
    			height = nb_buttons*MSS_Button.BUTTON_INIT_SIZE + 7*nb_buttons;
    		}
     
    		this.orientation = orientation;
    		this.setOpaque(false);
    		this.setPreferredSize(new Dimension(width, height));
    		this.setSize(new Dimension(width, height));
     
    		this.setLayout(new FlowLayout(FlowLayout.LEFT));
    	}
     
     
    	@Override
    	protected void paintComponent(Graphics g) {
    		super.paintComponent(g);
    		Graphics2D g2d = (Graphics2D)g;
    		g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f));
    		g2d.setColor(Color.WHITE);
     
    		if(orientation == HORIZONTAL)
    		{
    			g2d.fillRoundRect(0, 0, getWidth(), MSS_Button.BUTTON_INIT_SIZE,30,30);
    		}
    		else if(orientation == VERTICAL)
    		{
    			g2d.fillRoundRect(0, 0, MSS_Button.BUTTON_INIT_SIZE, getHeight(),30,30);
    		}	
    	}
    }
    En espérant que tu pourras trouver quelque chose d'intéressant !
    Merci de t'intéresser au problème.
    Je pense (j'espère que le code est assez propre).

    Thomas

  8. #8
    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
    Bon je viens de voir çà sur une grande fenêtre, je ne vois pas de ralentissements flagrants (bon un poil de temps en temps mais rien d'énorme).

    En fait le problème vient de la conception, tu a mis un time par item quand il en faudrait un global en fait, donc tu lances N thread dans la nature alors que tu pourrais en avoir un seul.

    CF par exemple le sujet sur le blog suivant (qui n'à rien à voir avec Java, il s'agit d'un des gourous de KDE, et çà parle Qt, mais el principe reste le même: avoir un seul timer pour gérer l'ensemble des anims plutôt qu'un timer par anim)

    http://aseigo.blogspot.com/2008/02/a...taneously.html
    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.

  9. #9
    Membre à l'essai
    Profil pro
    Inscrit en
    Juin 2007
    Messages
    53
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2007
    Messages : 53
    Points : 18
    Points
    18
    Par défaut
    Ca voudrait dire que je mets mon timer où dans ce cas là ? Dans ma barre d'outil ? Mais si je le mets dans la barre d'outil, comment savoir sur quel bouton je me trouve ? L'idée me paraît intelligente, puisque là il est clair que ça fait bcp de timers, mais j'ai du mal à voir comment la mettre en oeuvre.

    Thomas

    PS : Personnellement, quand je mets les boutons dans la barre, puis la barre dans une grande fenêtre, là ça rame bien quand même.

  10. #10
    Modérateur
    Avatar de dinobogan
    Homme Profil pro
    ingénieur
    Inscrit en
    Juin 2007
    Messages
    4 073
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France

    Informations professionnelles :
    Activité : ingénieur
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juin 2007
    Messages : 4 073
    Points : 7 163
    Points
    7 163
    Par défaut
    Idem que Sinok. J'ai testé sur ma machine, en pleine écran avec 10 buttons dans la bar, ça tourne bien.
    N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java
    Que la force de la puissance soit avec le courage de ta sagesse.

  11. #11
    Membre à l'essai
    Profil pro
    Inscrit en
    Juin 2007
    Messages
    53
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2007
    Messages : 53
    Points : 18
    Points
    18
    Par défaut
    Ah bah vous avez de la chance vous !
    Mais bon vous avez peut-être des supers bécanes...?

    Ceci dit, je peux peut-être effectivement gagner en performances en utilisant un seul timer. Si qqun a une piste pour la mise en oeuvre, je suis preneur. Parce que ça me ferait mal au coeur de devoir abandonner ces boutons qui me plaisent bien !

    Thomas.

  12. #12
    Modérateur
    Avatar de dinobogan
    Homme Profil pro
    ingénieur
    Inscrit en
    Juin 2007
    Messages
    4 073
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France

    Informations professionnelles :
    Activité : ingénieur
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juin 2007
    Messages : 4 073
    Points : 7 163
    Points
    7 163
    Par défaut
    Citation Envoyé par anaxa_gore Voir le message
    Ah bah vous avez de la chance vous !
    Mais bon vous avez peut-être des supers bécanes...?

    Ceci dit, je peux peut-être effectivement gagner en performances en utilisant un seul timer. Si qqun a une piste pour la mise en oeuvre, je suis preneur. Parce que ça me ferait mal au coeur de devoir abandonner ces boutons qui me plaisent bien !

    Thomas.
    Tu peux par exemple utiliser un singleton AnimThread utililé par tous les boutons. Lorsque la souris entre dans un bouton, il se poste lui même dans la file d'attente du Thread pour l'agrandissement. Lorsque la souris sort, il se notifie lui même au thread dans la liste des boutons à réduire. Le Thread le supprime alors de la liste des boutons à agrandir.
    A toi de voir les problèmes d'accès concurrent aux listes, mais c'est une première idée
    N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java
    Que la force de la puissance soit avec le courage de ta sagesse.

  13. #13
    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 fait il suffit d'avoir un Timer Swing qui envoie un évènement toutes les x millisecondes (définition de base d'un timer Swing). Il suffit de le mettre à disposition dans ton JPanel, puis faire en sorte que tes Buttons écoutent les ActionEvent levés par ce timer. charge à eux ensuite de faire ce qu'il faut à chaque fois qu'ils reçoivent un Event (ne rien faire, augmenter leur taille si ZommIn, diminuer leur taille si ZoomOut).
    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.

  14. #14
    Membre à l'essai
    Profil pro
    Inscrit en
    Juin 2007
    Messages
    53
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2007
    Messages : 53
    Points : 18
    Points
    18
    Par défaut
    Bon alors je reviens de we et je regarde un peu vos propositions pour n'avoir qu'un seul thread d'animation.
    Sinok, où trouve-t-on le TimerSwing ? Ce n'est pas un composant inclus directement dans le JDK on dirait ?

    Par ailleurs, si je comprends bien, tu veux dire que en fait toutes les millisecondes (par exemple), ce timer génère un évènement qui peut être reçu par mes boutons. Lorsque cet évènement arrive, chaque bouton regarde si la souris est "sur lui" ou inversement et réalise l'action de zoom in ou out... c'est bien ça ? La durée de l'action de zoom in ou out est donc donnée par le timerSwing. C'est bien ça ?

    Thomas

  15. #15
    Membre à l'essai
    Profil pro
    Inscrit en
    Juin 2007
    Messages
    53
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2007
    Messages : 53
    Points : 18
    Points
    18
    Par défaut
    Juste pour préciser : je pensais que SwingTimer était une classe. J'ai trouvé en fait Timer dans le package swing. Désolé pour la question bête.

    T.

  16. #16
    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
    Et désolé pour la coquille (oubli de l'espace entre Timer et Swing)
    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.

  17. #17
    Membre à l'essai
    Profil pro
    Inscrit en
    Juin 2007
    Messages
    53
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2007
    Messages : 53
    Points : 18
    Points
    18
    Par défaut
    Bon eh bien je ne comprends pas. J'ai modifié mon bouton et ma barre de la manière suivante (avec le timer swing) :

    Bouton :
    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
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
     
    public class MSS_Button extends JComponent implements ActionListener {
    	public static final long serialVersionUID = 1;
     
    	/** The initial size of a button. */
    	public static final int BUTTON_INIT_SIZE = 60;
    	/** The final size of a button. */
    	public static final int BUTTON_FINAL_SIZE = 80;
     
    	/** The actual size of button. */
    	public int size = 60;
     
    	/** A boolean which says if we are zooming in. */
    	private boolean isZoomIn = false;
    	/** A boolean which says if we are zooming out. */
    	private boolean isZoomOut = false;
     
    	/** The button picture url. */
    	private ImageIcon icon = null;
     
    	/** The transparency of picture to display. */
    	private float transparency = 0.4f;
     
    	/**
             * Constructor.
             * @param picture       The url to the picture to display on the button.
             */
    	public MSS_Button(URL picture) {
    		super();
    		icon = new ImageIcon(picture);
    		this.setOpaque(false);
    		this.setSize(BUTTON_INIT_SIZE, BUTTON_INIT_SIZE);
    		this.setPreferredSize(new Dimension(BUTTON_INIT_SIZE, BUTTON_INIT_SIZE));
    		this.addMouseListener(new MSS_Button_MouseListener());	
    	}
     
    	/**
             * Set the current transparency to use
             * for displaying the button.
             * 
             * @param       trans   The transparecy to use.
             */
    	public void setTransparency(float trans)
    	{
    		transparency = trans;
    	}
     
     
     
    	@Override
    	public void update(Graphics g) {
    		paint(g);
    	}
     
    	@Override
    	public void paint(Graphics g) {
    		super.paint(g);
    		Graphics2D g2d = (Graphics2D)g;
    		g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,transparency));
    		g2d.drawImage(icon.getImage(),0,0,getWidth(),getHeight(),null);
    		g2d.dispose();
    	}
     
    	/**
             * This class implements the graphical behaviour of an MSS_ActionButton
             * @author Thomas Bonavia
             *
             * @see MouseListener.
             * @see MSS_ActionButton.
             */
    	private class MSS_Button_MouseListener implements MouseListener
    	{	
    		/**
                     * When the mouse first button is pressed on the {@code MSS_ActionButton},
                     * The icon becomes opaque.
                     * @param       arg0    The mouse event.
                     */
    		@Override
    		public void mousePressed(MouseEvent arg0) {
    			MSS_Button b = (MSS_Button)arg0.getSource();
    			if(arg0.getButton() == MouseEvent.BUTTON1)
    			{
    				b.setTransparency(1.0f);
    			}
    				b.repaint();
    		}
     
    		/**
                     * When the mouse first button is release on the {@code MSS_ActionButton},
                     * The icon becomes semi-transparent (like in {@code MouseEntered}).
                     * @param       arg0    The mouse event.
                     */
    		@Override
    		public void mouseReleased(MouseEvent arg0) {
    			MSS_Button b = (MSS_Button)arg0.getSource();
    			if(arg0.getButton() == MouseEvent.BUTTON1)
    			{
    				b.setTransparency(0.7f);
    			}
    			b.repaint();
    		}
     
    		/**
                     * When the mouse enter on the {@code MSS_ActionButton},
                     * The icon becomes semi-transparent.
                     * @param       arg0    The mouse event.
                     */
    		@Override
    		public void mouseEntered(MouseEvent arg0) {
    			MSS_Button b = (MSS_Button)arg0.getSource();
    			b.setTransparency(0.7f);
    			isZoomIn = true;
    			isZoomOut= false;
    		}
     
    		/**
                     * When the mouse exit the {@code MSS_ActionButton},
                     * The icon becomes more transparent.
                     * @param       arg0    The mouse event.
                     */
    		@Override
    		public void mouseExited(MouseEvent arg0) {
    			MSS_Button b = (MSS_Button)arg0.getSource();
    			b.setTransparency(0.4f);
    			isZoomIn = false;
    			isZoomOut= true;
    		}
     
    		@Override
    		public void mouseClicked(MouseEvent arg0) {}
    	}
     
    	@Override
    	public void actionPerformed(ActionEvent e) {
    		if(size <= BUTTON_FINAL_SIZE && isZoomIn)
    		{
    			size = size+2;
    		}
    		if(size >= BUTTON_INIT_SIZE && isZoomOut)
    		{
    			size = size-2;
    		}
    		this.setSize(new Dimension(size,size));
    	}
     
    }
    La barre :
    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
     
    public class MSS_ButtonBar extends JComponent {
    public static final long serialVersionUID = 1;
     
    	/** The bar has a vertical orientation. */
    	public static final int VERTICAL = 1;
    	/** The bar has an horizontal orientation. */
    	public static final int HORIZONTAL = 2;
    	/** The orientation defined by the user. */
    	private int orientation = HORIZONTAL;
     
    	/** A swing timer generating events for {@code MSS_Button}. */
    	private Timer animTimer;
     
    	/**
             * Constructor.
             * This constructor creates a button bar with size adapted to
             * the number of buttons the user wants to include in.
             * 
             * @param       nb_buttons      The initial number of {@code MSS_Button}s.
             * @param       orientation     The orientation of the bar :
             * <ul>
             *      <li>Vertical    : {@code MSS_Button.VERTICAL}.</li>
             *      <li>Horizontal  : {@code MSS_BUTTON.HORIZONTAL}.</li>
             * </ul> 
             */
    	public MSS_ButtonBar(int nb_buttons, int orientation)
    	{
    		super();
    		int width = 0;
    		int height = 0;
     
    		if(orientation == HORIZONTAL)
    		{
    			width = nb_buttons*MSS_Button.BUTTON_INIT_SIZE + 7*nb_buttons;
    			height = MSS_Button.BUTTON_FINAL_SIZE + 10;
    		}
    		else if(orientation == VERTICAL)
    		{
    			width = MSS_Button.BUTTON_FINAL_SIZE + 10;
    			height = nb_buttons*MSS_Button.BUTTON_INIT_SIZE + 7*nb_buttons;
    		}
     
    		this.orientation = orientation;
    		this.setOpaque(false);
    		this.setPreferredSize(new Dimension(width, height));
    		this.setSize(new Dimension(width, height));
     
    		this.setLayout(new FlowLayout(FlowLayout.LEFT));
    		this.animTimer = new Timer(10,null);
    		this.animTimer.start();
    	}
     
     
    	@Override
    	public Component add(Component comp) {
    		animTimer.addActionListener((MSS_Button)comp);
    		return super.add(comp);
    	}
     
    	@Override
    	protected void paintComponent(Graphics g) {
    		super.paintComponent(g);
    		Graphics2D g2d = (Graphics2D)g;
    		g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f));
    		g2d.setColor(Color.WHITE);
     
    		if(orientation == HORIZONTAL)
    		{
    			g2d.fillRoundRect(0, 0, getWidth(), MSS_Button.BUTTON_INIT_SIZE,30,30);
    		}
    		else if(orientation == VERTICAL)
    		{
    			g2d.fillRoundRect(0, 0, MSS_Button.BUTTON_INIT_SIZE, getHeight(),30,30);
    		}	
    	}
    }
    J'observe toujours un ralentissement inadmissible pour une application lorsque je passe en plein écran ma fenêtre. Si quelqu'un a une idée.
    Voilà la config du pc sur lequel je travaille... au cas où :

    - Windows XP pro,
    - processeur intel core 2 duo T7100 1.8GHz,
    - 2 Go de RAM
    - NVIDIA QUADRO FX 1600M

    Je lance l'application sous Eclipse... mais je ne pense pas que ce soit ça qui puisse me ralentir ?

    T.

  18. #18
    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
    Je doute quand à ce qui concerne ton problème de ralentissments, ici çà passe sans le moindre PB, même en activant l'antialiasing et l'interpolation bilinéaire au niveau du dessin java2d.

    J'ai juste viré la redéfinition de updateUI et redéfini la méthode paintComponent plutôt que la méthode paint.

    C'est à se demander si la source de tes redimensionnements ne se trouverait pas ailleurs.

    Version de ta classe MSS_Button légèrement corrigée pour être plus swing dans l'esprit:

    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
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
     
    import java.awt.AlphaComposite;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.net.URL;
     
    import javax.swing.ImageIcon;
    import javax.swing.JComponent;
     
    public class MSS_Button extends JComponent implements ActionListener {
        public static final long serialVersionUID = 1;
     
        /** The initial size of a button. */
        public static final int BUTTON_INIT_SIZE = 60;
        /** The final size of a button. */
        public static final int BUTTON_FINAL_SIZE = 80;
     
        /** The actual size of button. */
        public int size = 60;
     
        /** A boolean which says if we are zooming in. */
        private boolean isZoomIn = false;
        /** A boolean which says if we are zooming out. */
        private boolean isZoomOut = false;
     
        /** The button picture url. */
        private ImageIcon icon = null;
     
        /** The transparency of picture to display. */
        private float transparency = 0.4f;
     
        /**
         * Constructor.
         * @param picture    The url to the picture to display on the button.
         */
        public MSS_Button(URL picture) {
            super();
            icon = new ImageIcon(picture);
            this.setOpaque(false);
            this.setSize(BUTTON_INIT_SIZE, BUTTON_INIT_SIZE);
            this.setPreferredSize(new Dimension(BUTTON_INIT_SIZE, BUTTON_INIT_SIZE));
            this.addMouseListener(new MSS_Button_MouseListener());    
        }
     
        /**
         * Set the current transparency to use
         * for displaying the button.
         * 
         * @param    trans    The transparecy to use.
         */
        public void setTransparency(float trans)
        {
            transparency = trans;
        }            
     
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D)g;
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,transparency));
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.drawImage(icon.getImage(),0,0,getWidth(),getHeight(),null);
            g2d.dispose();
        }
     
        /**
         * This class implements the graphical behaviour of an MSS_ActionButton
         * @author Thomas Bonavia
         *
         * @see MouseListener.
         * @see MSS_ActionButton.
         */
        private class MSS_Button_MouseListener extends MouseAdapter
        {    
            /**
             * When the mouse first button is pressed on the {@code MSS_ActionButton},
             * The icon becomes opaque.
             * @param    arg0    The mouse event.
             */
            @Override
            public void mousePressed(MouseEvent arg0) {
                MSS_Button b = (MSS_Button)arg0.getSource();
                if(arg0.getButton() == MouseEvent.BUTTON1)
                {
                    b.setTransparency(1.0f);
                }
                    b.repaint();
            }
     
            /**
             * When the mouse first button is release on the {@code MSS_ActionButton},
             * The icon becomes semi-transparent (like in {@code MouseEntered}).
             * @param    arg0    The mouse event.
             */
            @Override
            public void mouseReleased(MouseEvent arg0) {
                MSS_Button b = (MSS_Button)arg0.getSource();
                if(arg0.getButton() == MouseEvent.BUTTON1)
                {
                    b.setTransparency(0.7f);
                }
                b.repaint();
            }
     
            /**
             * When the mouse enter on the {@code MSS_ActionButton},
             * The icon becomes semi-transparent.
             * @param    arg0    The mouse event.
             */
            @Override
            public void mouseEntered(MouseEvent arg0) {
                MSS_Button b = (MSS_Button)arg0.getSource();
                b.setTransparency(0.7f);
                isZoomIn = true;
                isZoomOut= false;
            }
     
            /**
             * When the mouse exit the {@code MSS_ActionButton},
             * The icon becomes more transparent.
             * @param    arg0    The mouse event.
             */
            @Override
            public void mouseExited(MouseEvent arg0) {
                MSS_Button b = (MSS_Button)arg0.getSource();
                b.setTransparency(0.4f);
                isZoomIn = false;
                isZoomOut= true;
            }
     
            @Override
            public void mouseClicked(MouseEvent arg0) {}
        }
     
        public void actionPerformed(ActionEvent e) {
            if(size <= BUTTON_FINAL_SIZE && isZoomIn)
            {
                size = size+2;
            }
            if(size >= BUTTON_INIT_SIZE && isZoomOut)
            {
                size = size-2;
            }
            this.setSize(new Dimension(size,size));
        }
     
    }
    Sinon comment ajoutes tu ta barre à ton appli ? Je me demande si ton SpringLayou ne serait pas responsable du problème (recalcul du layout à chaque repaint)
    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.

  19. #19
    Membre à l'essai
    Profil pro
    Inscrit en
    Juin 2007
    Messages
    53
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2007
    Messages : 53
    Points : 18
    Points
    18
    Par défaut
    Merci pour les petites modifications "swing spirit" .

    J'ajoute ma barre, puis mes boutons de la façon suivante :
    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
     
    	public static void main(String[] args) throws ParseException, UnsupportedLookAndFeelException {		
    		// Frame parameters
    		JFrame frame = new JFrame("Test_MSS_ActionButton");
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.getContentPane().setLayout(new BorderLayout());
    		frame.setSize(Toolkit.getDefaultToolkit().getScreenSize());
    		frame.getContentPane().setBackground(Color.YELLOW);
     
    		// Preparing Icon for our button
    		URL image = frame.getClass().getResource("/tests_icons/earth.png");
     
    		// Buttons parameters
    		MSS_Button button1 = new MSS_Button(image);
    		button1.setName("button1");
    		button1.setToolTipText("A test of MSS_ActionButton 1");
    		MSS_Button button2 = new MSS_Button(image);
    		button2.setName("button2");
    		button2.setToolTipText("A test of MSS_ActionButton 2");
    		MSS_Button button3 = new MSS_Button(image);
    		button3.setName("button3");
    		button3.setToolTipText("A test of MSS_ActionButton 3");
    		MSS_Button button4 = new MSS_Button(image);
    		button4.setName("button4");
    		button4.setToolTipText("A test of MSS_ActionButton 4");
    		MSS_Button button5 = new MSS_Button(image);
    		button5.setName("button5");
    		button5.setToolTipText("A test of MSS_ActionButton 5");
    		MSS_Button button6 = new MSS_Button(image);
    		button6.setName("button6");
    		button6.setToolTipText("A test of MSS_ActionButton 6");
    		MSS_Button button7 = new MSS_Button(image);
    		button7.setName("button7");
    		button7.setToolTipText("A test of MSS_ActionButton 7");
     
    		// ButtonsBar parameters
    		MSS_ButtonBar bb = new MSS_ButtonBar(7,MSS_ButtonBar.VERTICAL);
    		bb.setName("MSS");
    		bb.add(button1);
    		bb.add(button2);
    		bb.add(button3);
    		bb.add(button4);
    		bb.add(button5);
    		bb.add(button6);
    		bb.add(button7);
     
    		JPanel panel = new JPanel(new FlowLayout());
    		panel.setPreferredSize(new Dimension(100,9));
    		panel.setOpaque(false);
     
    		panel.add(bb);
    		frame.getContentPane().add(panel,BorderLayout.WEST);
    		frame.setVisible(true);
    	}
    Merci de ton aide.
    Thomas

  20. #20
    Membre à l'essai
    Profil pro
    Inscrit en
    Juin 2007
    Messages
    53
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2007
    Messages : 53
    Points : 18
    Points
    18
    Par défaut
    PS : on peut enlever sans problème le JPanel supplémentaire bien sûr...

    PS2 : quand je retire la semi-transparence de la barre de boutons, je constate une LEGERE amélioration du rendu de l'animation.

Discussions similaires

  1. [Stratégie] Animation de chargement pendant l'affichage des pages
    Par tibouchou dans le forum Développement Web en Java
    Réponses: 15
    Dernier message: 18/04/2007, 11h48
  2. enlever animations JButton
    Par barbiche dans le forum AWT/Swing
    Réponses: 2
    Dernier message: 23/03/2007, 15h09
  3. [Stratégie] Afficher une animation dans un JScrollPane
    Par patmaba dans le forum AWT/Swing
    Réponses: 8
    Dernier message: 11/10/2005, 09h49
  4. [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