java getGraphics()

Started by
3 comments, last by bitshit 15 years, 8 months ago
I have 2 class files, the first one is the main applet file and the other has the paint method in it. When I call the paint method from the main applet file, the grahics dont get drawn, the applet just goes grey. These are my 2 files: mainApplet.java

import javax.swing.JApplet;

public class mainApplet extends JApplet {
	paintMethod paintString = new paintMethod();
	public void init(){
		paintString.paint(getGraphics());
	}
}

paintMethod.java

import java.awt.Graphics;
import java.awt.Font;

public class paintMethod {
	public void paint(Graphics g){
		g.setFont(new Font("Arial", Font.BOLD, 20));
		g.drawString("Hello", 5, 15);
	}
}

All I manage to get is a grey screen. I know it will end up being a simple mistake that I have made. But if anyone could help, that would be great :)
Advertisement
you're supposed to use the paint method overriden from the applet subclass. In other words, you should only have one class here, and it should look like this:

import javax.swing.*;import java.awt.*;public class mainApplet extends JApplet {    public void paint(Graphics g) {        g.setFont(new Font("Arial",Font.BOLD,20));        g.drawString("Hello",5,15));    }}


or even better

import javax.swing.*;import java.awt.*;public class mainApplet extends JApplet {    private Font font;        public void init() {        font = new Font("Arial",Font.BOLD,20);    }        public void paint(Graphics g) {        g.setColor(Color.white);        g.fillRect(0,0,getWidth(),getHeight());        g.setColor(Color.black);        g.setFont(font);        g.drawString("Hello",5,15));    }}
paint() is a function that Java calls for you. You should not call it yourself. The idea is that whenever your applet needs to be redrawn (e.g. because the user had a window on top of yours, and then moved it away), it will get called, with an appropriate Graphics instance passed in automatically.
Ah I understand, I guess I didnt read the java tutorial properly.

Thanks guys :)
While it's true Java calls update() & paint() automatically for you when present (this is called passive rendering), you can draw yourself to the graphics context anytime you want, without relying on the JVM calling paint() (this is called active rendering, which is more suitable for games).

Active rendering works like you do it in the example, but not in the init phase of the applet. While you're in the start or run the graphics context is available for drawing to it...

This topic is closed to new replies.

Advertisement