Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Adding a gif to a java app

  • 15-01-2003 08:06PM
    #1
    Closed Accounts Posts: 1,518 ✭✭✭


    Does anybody know how to add an image in a Java application? I've been given the code (below) but when I run it the gif won't show up even when I save the gif in the project. Nobody in the class seems to know how to do it and I'm rubbish at programming.

    import java.awt.*;

    public class Whatever extends Frame
    {
    Image img;

    public Whatever()
    {
    img = Toolkit.getDefaultToolkit().createImage("x.gif");
    setSize(200,200);

    show();
    }

    public void paint(Graphics g)
    {
    g.drawImage(img,10,30,null);
    }

    public static void main(String args[])
    {
    Whatever x=new Whatever();
    x.repaint();
    }
    }


    Thanks,
    K


Comments

  • Registered Users, Registered Users 2 Posts: 1,481 ✭✭✭satchmo


    You might notice that the image shows up if you drag the window off the screen and back on again. The problem is that you're trying to display the image right after you load it (with createImage()), and if the image isn't completely loaded then it won't display properly. When you drag the window off & on again it forces a repaint, so then your image shows up.

    The solution is either to continuously repaint the frame, or to wait until the image is loaded before painting it. The latter can be done with a MediaTracker, put these lines after your createImage() call:
    MediaTracker tracker=new MediaTracker(this);
    tracker.addImage(img,0); 
    try{tracker.waitForAll();}catch(InterruptedException ie){System.exit(1);}
    
    This waits until the tracked image is completely loaded before proceeding to show the frame.


  • Closed Accounts Posts: 1,518 ✭✭✭Kalina


    Thanks a lot for your suggestion, Jazz!!:)
    I got it working.


Advertisement