Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    Feb 2010
    Posts
    95
    Thanks
    14
    Thanked 0 Times in 0 Posts

    Applet code works in paint(...) but not in init()

    Hi!
    Why does the following code work :
    Code:
        public class Game extends Applet
        {
           public void init() {}
    
           public void paint(Graphics g)
           {
               Image img = getImage(getCodeBase(), "Ball.png");
               BufferedImage bi = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
               Graphics2D g2 = bi.createGraphics();
               g2.drawImage(img, 50, 50, this);
               g.drawImage(bi, 0, 0, this);
           }
       }
    But not this:
    Code:
    public class Game extends Applet
    {
        private BufferedImage bi = null;
    
        public void init()
        {
            Image img = getImage(getCodeBase(), "Ball.png");
            bi = new BufferedImage(getWidth(), getHeight(),    BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2 = bi.createGraphics();
            g2.drawImage(img, 50, 50, this);
        }
    
        public void paint(Graphics g)
        {
            
            g.drawImage(bi, 0, 0, this);
        }
    }

  • #2
    Regular Coder brad211987's Avatar
    Join Date
    Sep 2005
    Location
    Ohio
    Posts
    631
    Thanks
    10
    Thanked 50 Times in 50 Posts
    More or less it's because of the applet lifecycle. init() is called when the applet is initialized, but that does not mean it is ready to display anything. Typically paint() is called automatically when the applet is ready on the screen to render. Nothing can be displayed before that point so putting that code in the init() phase has no purpose.

  • #3
    New Coder
    Join Date
    Feb 2010
    Posts
    95
    Thanks
    14
    Thanked 0 Times in 0 Posts
    My code doesn´t display anything in init(), it only assigns the buffered image(bi). You should be able to assign values when initializing the applet or have I missed something.

  • #4
    New Coder
    Join Date
    Aug 2009
    Location
    Cochin,India
    Posts
    39
    Thanks
    2
    Thanked 1 Time in 1 Post
    May be because you are using Graphics object in the init() method..
    init() start() and paint() are the life cycle methods of an applet are invoked automatically in that order.
    All graphics related things are to be done in paint() methods ie. after applet is initialized and started.



  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •