Hi to all,
I don't understand how to dynamically update the visualization of a
component, that is:
I need to change the icon of a JButton and during the execution of the
program it may change more times (two or three [see sample code]). What I
see is only the last change. I tryed updateUI() method or similar without
result.
What could I do to view the middle change?
Thanks
<-----start here----->
button1.setIcon(new ImageIcon("images/img1.JPG"));
...
try{ Thread.sleep(1000); }
catch (InterruptedException ex) {}
button1.setIcon(new ImageIcon("images/img2.JPG"));
...
try{ Thread.sleep(1000); }
catch (InterruptedException ex) {}
button1.setIcon(new ImageIcon("images/img3.JPG"));
<-----end here-----
Andrew Chase - 24 Feb 2004 22:26 GMT
Hi,
Sounds like your new to the Swing Thread Model. First, go to
http://java.sun.com and do a search on "Swing Thread" and poke around some
of the many articles on Sun's site about the Swing Thread Model.
But, for immediate gratification, you may be able to get away with using the
static method SwingUtilities.invokeLater method (but you may need to use a
SwingWorker, anyone else, please feel free to correct me). The
SwingUtilities.invokeLater is a handy little method to use to invoke methods
that update the UI in a responsible and timely manner. For your code it
would look like this:
SwingUtilities.invokeLater(new Runnable(){
public void run(){
button1.setIcon(image);
}
});
Remember, since button1 is being used in an inner class it will either need
to be a class level variable or a final variable.
Have fun,
Andrew
> Hi to all,
> I don't understand how to dynamically update the visualization of a
[quoted text clipped - 19 lines]
>
> <-----end here-----
Thomas Weidenfeller - 25 Feb 2004 08:22 GMT
> Hi to all,
> I don't understand how to dynamically update the visualization of a
[quoted text clipped - 4 lines]
> result.
> What could I do to view the middle change?
FAQ. You are blocking the event displatching thread.
/Thomas
NetExplorer - 29 Feb 2004 09:20 GMT
The java tutorial on sun's site has a good example similar to what you are
trying to do (see the "Performing Animation" section, which covers your
situation as well, I think). I'm not sure if there is any event in
particular that causes your icon to change or if it just needs to do it at a
selected interval. In the latter case, take a look at the SwingTimer class
in that section of the tutorial.
In either case, add the label as an listener (to the timer for it to tick,
or to whatever causes you to want to change the icon) and when the label
receives the message, put code in your label to perform your change. If you
aren't using the SwingTimer class which is thread-safe already, the
invokeLater mentioned by others is recommended.
> > Hi to all,
> > I don't understand how to dynamically update the visualization of a
[quoted text clipped - 8 lines]
>
> /Thomas