Sign in to follow this  
thephil

java getGraphics()

Recommended Posts

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 :)

Share this post


Link to post
Share on other sites
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));
}
}

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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...

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this