View Single Post
  #2 (permalink)  
Old 12-05-2007, 12:47 AM
hardwired hardwired is offline
Senior Member
 
Join Date: Jul 2007
Posts: 1,189
hardwired is on a distinguished road
Using a non–live (eg, member variable) graphics context reference will generally result in a NullPointerException. The way to draw in java is to set up your graphic component to be able to draw the current state of its enclosing class at any time and communicate with it from your event code to change its state and tell it to repaint itself to reflect the changes. All drawing should be placed inside or called from the relevant painting method, here, paintComponent. More like this:
Code:
import java.awt.*; import javax.swing.*; public class MainScene { private JFrame theFrame; private Scene theSceneGenerator; public MainScene(){ theFrame = new JFrame(); theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); theFrame.setSize(400,400); theFrame.setLocation(200,200); theFrame.setVisible(true); loadSceneIntoFrame(); } private void loadSceneIntoFrame(){ theSceneGenerator = new Scene(); theFrame.getContentPane().add(theSceneGenerator); // Tell the frame to make a new layout/inventory // of its children when making changes after // realization. theFrame.validate(); // Sometimes you need this next line, sometimes not; // you have to try for the minimum in each case. // theFrame.repaint(); Shape test = createRectangle(20,20,200,100); theSceneGenerator.setFill(true); theSceneGenerator.setFillColor(new Color(200,120,0)); theSceneGenerator.setShape(test); } private Shape createRectangle(int offsetX, int offsetY, int shapeWidth, int shapeHeight){ //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 polygon = new Polygon(xPoints,yPoints,4); Rectangle rect = new Rectangle(offsetX, offsetY, shapeWidth, shapeHeight); // Both Polygon and Rectangle implement the Shape // interface so you can return either one okay. return rect; //polygon; } public static void main(String[] args) { new MainScene(); } } class Scene extends JPanel { private boolean fill = false; Color fillColor; Shape theShape; protected void paintComponent(Graphics renderScene){ super.paintComponent(renderScene); Graphics2D g2 = (Graphics2D)renderScene; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if(fill) { g2.setPaint(fillColor); g2.fill(theShape); } g2.setPaint(Color.blue); g2.draw(theShape); System.out.println("test"); } public void setFill(boolean fill){ this.fill = fill; repaint(); } public void setFillColor(Color color) { fillColor = color; repaint(); } public void setShape(Shape theShape){ this.theShape = theShape; repaint(); } }
Reply With Quote