简体   繁体   中英

why we cant draw a String using graphics object in this example

I want to draw a string using a init method but if use inside start method then its work fine. Please explain me

    public class Canv extends Applet //applet class 
    {   
        public void start()
        {

        }
         public void init()
        {                                     
            System.out.println("hi");
            Canvas c=new Canvas();              // want to print String in canvas

            c.setSize(500,500);
            c.setBackground(Color.red);
            add(c);
            Graphics g=c.getGraphics();  
            g.drawString("hello buddy",60,60); 
        }
        public void paint(Graphics g)
        {

        }
        public void stop()
        {
            System.out.println("stop");
        }
    }

If you carefully read the API provided by Java, then you would see for init :

 * Called by the browser or applet viewer to inform
 * this applet that it has been loaded into the system. It is always
 * called before the first time that the <code>start</code> method is
 * called.
 * <p>
 * A subclass of <code>Applet</code> should override this method if
 * it has initialization to perform. For example, an applet with
 * threads would use the <code>init</code> method to create the
 * threads and the <code>destroy</code> method to kill them.

And for start :

 * Called by the browser or applet viewer to inform
 * this applet that it should start its execution. It is called after
 * the <code>init</code> method and each time the applet is revisited
 * in a Web page.

Obviously, the code that uses this interface to manipulate Java applets does not show the canvas written in the init() method because the UI at that point is not ready. It's just a marker for you that the container started initializing your app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM