Problem going outside paintComponent
I got two classes which can draw a scene/canvas on which I can paint stuff like circles, triangles etc.
If I draw a shape inside the paintComponent and then fill it, it works fine.
If I try to do the same thing from outside of the paintCompoment, using the same methods, it gives a nullPointerException.
The two classes:
Scene.java
Code:
// Created by Thez
// Created on 04 December 2007, 18:48
package crossfire;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.Shape;
import javax.swing.JPanel;
public class Scene extends javax.swing.JPanel {
private Graphics2D theScene;
//this overrides the original method to allow for modification
public void paintComponent(Graphics renderScene){
super.paintComponent(renderScene);
theScene = (Graphics2D)renderScene;
//Shape test = createRectangle(20,20,200,100);
//fillShape(theShape,new Color(200,120,0));
System.out.println("test");
}
//makes a fully filled drawing of the shape given
public void fillShape(Shape theShape, Color theColor){
theScene.setColor(theColor);
theScene.fill(theShape);
}
//makes an outline drawing of the shape given
public void drawShape(Shape theShape, Color theColor){
theScene.setColor(theColor);
theScene.draw(theShape);
}
//this creates a rectangle
public Shape createRectangle(int offsetX, int offsetY, int shapeWidth, int shapeHeight){
Shape newShape = null;
//set the size and position
int[] xPoints = {offsetX, offsetX + shapeWidth, offsetX + shapeWidth, offsetX};
int[] yPoints = {offsetY, offsetY, offsetY + shapeHeight, offsetY + shapeHeight};
//a rectangle always has 4 points/corners
Polygon theRectangle = new Polygon(xPoints,yPoints,4);
//make a shape out of it
newShape = theRectangle;
return newShape;
}
}
Main.java
Code:
//Created on 04-12-2007 18:26
//Created by Thez
package crossfire;
import java.awt.Color;
import java.awt.Shape;
import javax.swing.JFrame;
public class Main {
private Window theWindow;
private JFrame theFrame;
private Scene theSceneGenerator;
//load the window, note the dimensions are still needed if made fullscreen, in case the user minimizes
public Main(){
theWindow = new Window(false,true,800,600,"Test");
loadSceneIntoFrame();
}
//startup
public static void main(String[] args) {
new Main();
}
//this loads the scene class and puts it into the frame
public void loadSceneIntoFrame(){
//first we get the JFrame
theFrame = theWindow.getFrame();
theSceneGenerator = new Scene();
theFrame.getContentPane().add(theSceneGenerator);
Shape test = theSceneGenerator.createRectangle(20,20,200,100);
theSceneGenerator.fillShape(test,new Color(200,120,0));
}
}
Now I've been at it a few hours but I just can't seem to get it to work.
All I need is to able to draw and remove shapes from the scene/canvas outside the paintComponent.
Any ideas?