Search code examples
javagraphicsapplet

Trying to print text from a method other than paint()


I created an applet wherein I defined a method besides overriding the paint() method that uses the Graphics.drawString() method to display a text on the canvas. The problem I'm having is that I cannot call that method. This is because the method takes a Graphics class object as an argument and I cannot pass a Graphics class object as an argument while calling that function. (The callerMethod() is called in a certain situation.) Please see my code below and help. Thanks.

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

Solution

  • The myPrintMethod() should be called with a Graphics object being passed as actual parameter. The Graphics object g of the paint method can be passed to the myPrintMethod while calling it.

    public static void myPrintMethod(Graphics g){
        g.drawString("myPrintMethod",20,40); 
    }
    public void paint(Graphics g){
        g.drawString("Paint method",20,20);
        myPrintMethod(g);
    }    
    

    This will give the output:

    Paint method
    
    myPrintMethod