gpt4 book ai didi

java - 为什么在这个例子中我们不能使用图形对象绘制字符串

转载 作者:行者123 更新时间:2023-12-01 11:16:20 24 4
gpt4 key购买 nike

我想使用 init 方法绘制一个字符串,但如果使用内部 start 方法,那么它的工作正常。请解释一下

    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");
}
}

最佳答案

如果你仔细阅读Java提供的API,那么你会看到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.

对于开始:

 * 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.

显然,使用此接口(interface)操作 Java 小程序的代码不会显示 init() 方法中编写的 Canvas ,因为此时的 UI 尚未准备好。这只是容器开始初始化您的应用程序的一个标记。

关于java - 为什么在这个例子中我们不能使用图形对象绘制字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31789676/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com