尝试从 paint() 以外的方法打印文本
Trying to print text from a method other than paint()
我创建了一个小程序,其中除了覆盖使用 Graphics.drawString()[=16= 的 paint() 方法之外,我还定义了一个方法] 方法在 canvas 上显示文本。我遇到的问题是我无法调用该方法。这是因为该方法将 Graphics class 对象作为参数,而我在调用该函数时无法将 Graphics class 对象作为参数传递。 (在特定情况下会调用 callerMethod()。) 请参阅下面的代码并提供帮助。谢谢
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet {
@Override
public void init() {}
public void callerMethod() {
/*HERE I WANT TO CALL myPrintMethod()*/
myPrintMethod(GRAPHICS OBJECT);
}
public static void myPrintMethod(Graphics g) {
g.drawString("In method myPrintMethod",20,40);
}
@Override
public void paint(Graphics g) {
g.drawString("In method paint",20,20);
}
}
public class MyApplet extends Applet {
Graphics g1;
---------------
public void callerMethod() {
//call myPrintMethod();
}
public static void myPrintMethod() {
//Now you can paint here also
g1.drawString("In method myPrintMethod",20,40);
}
@Override
public void paint(Graphics g) {
g1 = g;
g.drawString("In method paint",20,20);
}
}
但是这个myPrintMethod()
应该在paint(.)
之后调用。
使用提供更多高级功能的Graphics2D
。
Graphics2D g2d = (Grapics2D) g;
调用 myPrintMethod() 时应将 Graphics 对象作为实际参数传递。调用时可以将paint方法的Graphics对象g传递给myPrintMethod。
public static void myPrintMethod(Graphics g){
g.drawString("myPrintMethod",20,40);
}
public void paint(Graphics g){
g.drawString("Paint method",20,20);
myPrintMethod(g);
}
这将给出输出:
Paint method
myPrintMethod
我创建了一个小程序,其中除了覆盖使用 Graphics.drawString()[=16= 的 paint() 方法之外,我还定义了一个方法] 方法在 canvas 上显示文本。我遇到的问题是我无法调用该方法。这是因为该方法将 Graphics class 对象作为参数,而我在调用该函数时无法将 Graphics class 对象作为参数传递。 (在特定情况下会调用 callerMethod()。) 请参阅下面的代码并提供帮助。谢谢
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet {
@Override
public void init() {}
public void callerMethod() {
/*HERE I WANT TO CALL myPrintMethod()*/
myPrintMethod(GRAPHICS OBJECT);
}
public static void myPrintMethod(Graphics g) {
g.drawString("In method myPrintMethod",20,40);
}
@Override
public void paint(Graphics g) {
g.drawString("In method paint",20,20);
}
}
public class MyApplet extends Applet {
Graphics g1;
---------------
public void callerMethod() {
//call myPrintMethod();
}
public static void myPrintMethod() {
//Now you can paint here also
g1.drawString("In method myPrintMethod",20,40);
}
@Override
public void paint(Graphics g) {
g1 = g;
g.drawString("In method paint",20,20);
}
}
但是这个myPrintMethod()
应该在paint(.)
之后调用。
使用提供更多高级功能的Graphics2D
。
Graphics2D g2d = (Grapics2D) g;
调用 myPrintMethod() 时应将 Graphics 对象作为实际参数传递。调用时可以将paint方法的Graphics对象g传递给myPrintMethod。
public static void myPrintMethod(Graphics g){
g.drawString("myPrintMethod",20,40);
}
public void paint(Graphics g){
g.drawString("Paint method",20,20);
myPrintMethod(g);
}
这将给出输出:
Paint method
myPrintMethod