1

I've been trying to print using the drawString() function of Graphics class in a method other than paint(). I've tried this program which was the solution to an earlier doubt, but this code is not working. Please find me the flaws. Thanks. Here's it below:

import java.awt.*;
import java.applet.*;

public class PaintIssue extends Applet {

    Graphics gg; //global Graphics object

    @Override
    public void init() {}

    @Override
    public void paint(Graphics g) {
        g.drawString("Output of paint method",20,20);
        myMethod(); //calling myMethod
    }

    public static void myMethod() {
        gg.drawString("Output of myMethod",20,40);
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1) Why code an applet? If it is due to the teacher specifying it, please refer them to [Why CS teachers should **stop** teaching Java applets](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets/). 2) Why use AWT? See [this answer](http://stackoverflow.com/questions/6255106/java-gui-listeners-without-awt/6255978#6255978) for many good reasons to abandon AWT using components in favor of Swing. – Andrew Thompson Feb 23 '16 at 00:21
  • Well I'm new to applets and AWT is the only thing I've learnt so far regarding graphics manipulation. I've been doing them for a year now. –  Feb 24 '16 at 15:48
  • You'll get better help & better answers, on Swing and desktop apps. – Andrew Thompson Feb 24 '16 at 15:51
  • I'm sure I will. I hope to start with Swing soon. Thanks. :) –  Feb 24 '16 at 15:57

1 Answers1

1

AWT doesn't have a concept of a "global graphics object". You have to pass down the Graphics object that your paint method receives.

    @Override
    public void paint(Graphics g) {
        g.drawString("Output of paint method",20,20);
        myMethod(g); //calling myMethod
    }

    public static void myMethod(Graphics g) {
        g.drawString("Output of myMethod",20,40);
    }
Thomas Kläger
  • 17,754
  • 3
  • 23
  • 34