Saving Graphics Object

Is it possible to transfer a Graphics Object to another Canvas so that I can use the painted graphics there?
I have a canvas, where some texts and boxes are painted. Now I want to start another Canvas, where the user can move a Pointer in the Graphic of the other Canvas.
So I thought I hand over the Graphics-Object to my new Canvas and overwrite my actual Graphics-Object. Now I want to paint a crosspointer and move it on the screen.
I hope anyone has understood this stupid question.
Great_T

You have to use "manual" double buffering:
private Image image = Image.creaneImage(this.getWeight(), this.getHeight());
private Graphics graphics = image.getGraphics();
Paint to graphics.
public void paint(Graphics g) {
g.drawImage(image, 0, 0, Graphics.TOP | Graphics.LEFT);
Then pass your image in the new Canvas and continue to paint to it's
Graphics object
I hope this is helpful.

Similar Messages

  • How to convert a Graphics object into a JPG image?

    I have this simple question about how to make a Graphics object into a JPG file...
    I just need the names of the classes or the packages ... I'll figure out the rest of the details...
    Thanks...

    Anyway this might come in handy
    JPEGUtils.java
    ============
    * Created on Jun 22, 2005 by @author Tom Jacobs
    package tjacobs.jpeg;
    import java.awt.Image;
    import java.awt.image.BufferedImage;
    import java.awt.image.RenderedImage;
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import javax.imageio.ImageIO;
    import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGEncodeParam;
    import com.sun.image.codec.jpeg.JPEGImageDecoder;
    import com.sun.image.codec.jpeg.JPEGImageEncoder;
    * Utilities for saving JPEGs and GIFs
    public class JPEGUtils {
         private JPEGUtils() {
              super();
         public static void saveJPEG(BufferedImage thumbImage, File file, double compression) throws IOException {
              BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
              saveJPEG(thumbImage, out, compression);
              out.flush();
              out.close();
         public static void saveJPEG(BufferedImage thumbImage, OutputStream out, double compression) throws IOException {
              JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
              JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
              compression = Math.max(0, Math.min(compression, 100));
              param.setQuality((float)compression / 100.0f, false);
              encoder.setJPEGEncodeParam(param);
              encoder.encode(thumbImage);
         public static BufferedImage getJPEG(InputStream in) throws IOException {
              try {
                   JPEGImageDecoder decode = JPEGCodec.createJPEGDecoder(in);
                   BufferedImage im = decode.decodeAsBufferedImage();
                   return im;
              } finally {
                   in.close();
         public static BufferedImage getJPEG(File f) throws IOException {
              InputStream in = new BufferedInputStream(new FileInputStream(f));
              return getJPEG(in);
         public static void saveGif(RenderedImage image, File f) throws IOException {
              saveGif(image, new FileOutputStream(f));
         public static void saveGif(RenderedImage image, OutputStream out) throws IOException {
    //          Last time I checked, the J2SE 1.4.2 shipped with readers for gif, jpeg and png, but writers only for jpeg and png. If you haven't downloaded the whole JAI, and you want a writer for gif (as well as readers and writers for several other formats) download:
    //          http://java.sun.com/products/java-media/jai/downloads/download-iio.html
              ImageIO.write(image, "gif", out);
         public static void main(String[] args) {
              // TODO Auto-generated method stub
    }

  • How to change font/ font color etc in a graphic object using JCombobox?

    Hello
    My program im writing recently is a small tiny application which can change fonts, font sizes, font colors and background color of the graphics object containing some strings. Im planning to use Jcomboboxes for all those 4 ideas in implementing those functions. Somehow it doesnt work! Any help would be grateful.
    So currently what ive done so far is that: Im using two classes to implement the whole program. One class is the main class which contains the GUI with its components (Jcomboboxes etc..) and the other class is a class extending JPanel which does all the drawing. Therefore it contains a graphics object in that class which draws the string. However what i want it to do is using jcombobox which should contain alit of all fonts available/ font sizes/ colors etc. When i scroll through the lists and click the one item i want - the graphics object properties (font sizes/ color etc) should change as a result.
    What ive gt so far is implemented the jcomboboxes in place. Problem is i cant get the font to change once selecting an item form it.
    Another problem is that to set the color of font - i need to use it with a graphics object in the paintcomponent method. In this case i dnt want to create several diff paint.. method with different property settings (font/ size/ color)
    Below is my code; perhaps you'll understand more looking at code.
    public class main...
    Color[] Colors = {Color.BLUE, Color.RED, Color.GREEN};
            ColorList = new JComboBox(Colors);
    ColorList.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ev) {
                     JComboBox cb = (JComboBox)ev.getSource();
                    Color colorType = (Color)cb.getSelectedItem();
                    drawingBoard.setBackground(colorType);
              });;1) providing the GUI is correctly implemented with components
    2) Combobox stores the colors in an array
    3) ActionListener should do following job: (but cant get it right - that is where my problem is)
    - once selected the item (color/ font size etc... as i would have similar methods for each) i want, it should pass the item into the drawingboard class (JPanel) and then this class should do the job.
    public class DrawingBoard extends JPanel {
           private String message;
           public DrawingBoard() {
                  setBackground(Color.white);
                  Font font = new Font("Serif", Font.PLAIN, fontSize);
                  setFont(font);
                  message = "";
           public void setMessage(String m) {
                message = m;
                repaint();
           public void paintComponent(Graphics g) {
                  super.paintComponent(g);
                  //setBackground(Color.RED);
                  Graphics2D g2 = (Graphics2D) g;
                  g2.setRenderingHint             
                  g2.drawString(message, 50, 50);
           public void settingFont(String font) {
                //not sure how to implement this?                          //Jcombobox should pass an item to this
                                   //it should match against all known fonts in system then set that font to the graphics
          private void settingFontSize(Graphics g, int f) {
                         //same probelm with above..              
          public void setBackgroundColor(Color c) {
               setBackground(c);
               repaint(); // still not sure if this done corretly.
          public void setFontColor(Color c) {
                    //not sure how to do this part aswell.
                   //i know a method " g.setColor(c)" exist but i need to use a graphics object - and to do that i need to pass it in (then it will cause some confusion in the main class (previous code)
           My problems have been highlighted in the comments of code above.
    Any help will be much appreciated thanks!!!

    It is the completely correct code
    I hope that's what you need
    Just put DrawingBoard into JFrame and run
    Good luck!
    public class DrawingBoard extends JPanel implements ActionListener{
         private String message = "message";
         private Font font = new Font("Serif", Font.PLAIN, 10);
         private Color color = Color.RED;
         private Color bg = Color.WHITE;
         private int size = 10;
         public DrawingBoard(){
              JComboBox cbFont = new JComboBox(GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames());
              cbFont.setActionCommand("font");
              JComboBox cbSize = new JComboBox(new Integer[]{new Integer(14), new Integer(13)});
              cbSize.setActionCommand("size");
              JComboBox cbColor = new JComboBox(new Color[]{Color.BLUE, Color.RED, Color.GREEN});
              cbColor.setActionCommand("color");
              JComboBox cbBG = new JComboBox(new Color[]{Color.BLUE, Color.RED, Color.GREEN});
              cbBG.setActionCommand("bg");
              add(cbFont);
              cbFont.addActionListener(this);
              add(cbSize);
              cbSize.addActionListener(this);
              add(cbColor);
              cbColor.addActionListener(this);
              add(cbBG);
              cbBG.addActionListener(this);
         public void setMessage(String m){
              message = m;
              repaint();
         protected void paintComponent(Graphics g){
              super.paintComponent(g);
              Graphics2D g2 = (Graphics2D)g;
              g2.setColor(bg);//set background color
              g2.fillRect(0,0, getWidth(), getHeight());          
              g2.setColor(color);//set text color
              FontRenderContext frc = g2.getFontRenderContext();
              TextLayout tl = new TextLayout(message,font,frc);//set font and message
              AffineTransform at = new AffineTransform();
              at.setToTranslation(getWidth()/2-tl.getBounds().getWidth()/2,
                        getWidth()/2 + tl.getBounds().getHeight()/2);//set text at center of panel
              g2.fill(tl.getOutline(at));
         public void actionPerformed(ActionEvent e){
              JComboBox cb = (JComboBox)e.getSource();
              if (e.getActionCommand().equals("font")){
                   font = new Font(cb.getSelectedItem().toString(), Font.PLAIN, size);
              }else if (e.getActionCommand().equals("size")){
                   size = ((Integer)cb.getSelectedItem()).intValue();
              }else if (e.getActionCommand().equals("color")){
                   color = (Color)cb.getSelectedItem();
              }else if (e.getActionCommand().equals("bg")){
                   bg = (Color)cb.getSelectedItem();
              repaint();
    }

  • Trying to move a graphics object using buttons.

    Hello, im fairly new to GUI's. Anyway I have 1 class which makes my main JFrame, then I have another 2 classes, one to draw a lil square graphics component (which iwanna move around) which is placed in the center of my main frame and then another class to draw a Buttonpanel with my buttons on which is placed at the bottom of my main frame.
    I have then made an event handling class which implements ActionListner, I am confused at how I can get the graphics object moving, and where I need to place the updateGUI() method which the actionPerformed method calls from inside the event handling class.
    I am aware you can repaint() graphics and assume this would be used, does anyone have a good example of something simular being done or could post any help or code to aid me, thanks!

    Yeah.. here's an example of custom painting on a JPanel with a box. I used a mouse as it was easier for me to setup than a nice button panel on the side.
    Anyways... it should make it pretty clear how to get everything setup, just add a button panel on the side. and use it to move the box instead of the mouse.
    -Js
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.event.MouseInputAdapter;
    public class MoveBoxAroundExample extends JFrame
         private final static int SQUARE_EDGE_LENGTH = 40;
         private JPanel panel;
         private int xPos;
         private int yPos;
         public MoveBoxAroundExample()
              this.setSize(500,500);
              this.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
              this.setContentPane(getPanel());
              xPos = 250;
              yPos = 250;
              this.setVisible(true);     
         private JPanel getPanel()
              if(panel == null)
                   panel = new JPanel()
                        public void paintComponent(Graphics g)
                             super.paintComponent(g);
                             g.setColor(Color.RED);
                             g.fillRect(xPos-(SQUARE_EDGE_LENGTH/2), yPos-(SQUARE_EDGE_LENGTH/2), SQUARE_EDGE_LENGTH, SQUARE_EDGE_LENGTH);
                   MouseInputAdapter mia = new MouseInputAdapter()
                        public void mousePressed(MouseEvent e)
                            xPos = e.getX();
                            yPos = e.getY();
                            panel.repaint();
                        public void mouseDragged(MouseEvent e)
                            xPos = e.getX();
                            yPos = e.getY();
                            panel.repaint();
                   panel.addMouseListener(mia);
                   panel.addMouseMotionListener(mia);
              return panel;
         public static void main(String args[])
              new MoveBoxAroundExample();
    }

  • Error while saving for Objective setting

    Hi,
    While saving the Objective setting templates i am getting the error as "Table HRPAD605 is not part of the Customizing object PDST T "
    <u>Error documentation is as follows</u>
    <b>Diagnosis</b>
    Entries in table HRPAD605 cannot be edited in connection with customizing object PDST      T as table HRPAD605 does not belong to customizing object PDST      T, according to the object definition.
    <b>System Response</b>
    The function terminates.
    <b>Procedure</b>
    Check whether the entered objects and keys are correct.Then check in the Implementation Guide whether the object was created correctly.
    Correct the object definition or the entry for the Transport Organizer interface.
    Thanks

    Hello,
    Most likely the is an inconsistency with the transport objects PDST and PDWS. Please run RHSOBJCH to correct this inconsistency.
    Afterwards you should be able to transport the templates via the catalog or via RHMOVE30. Please make sure that the category ID in the target system is the same otherwise you won't be able to locate the template.
    The report RHSOBJCH corrects the missing HR entries in the OBJS table.
    This step you need to perform only once. For OSA you need to overtake
    *5020 up to *5026, also PAD605,606 and 607 references.
    When you have done this (as said, only need to do it once) you can transport the categories and templates via the phap_catalog_pa transaction (righ-mouse click on the to be transported object).
    Hope this helps,
    Regards and Groetjes,
    Maurice

  • Error while saving the objects in ID

    Dear All,
    When I am saving the objects in ID, I am facing with the following error:
    <b>[SAP_NWMss][SQLServer JDBC Driver][SQLServer]Could not allocate space for object 'XI_DIRDATACHANNEL' in database 'XD1' because the 'PRIMARY' filegroup is full</b>
    Please guide how to solve this error.
    Warm regards,
    n.jain

    Hi Nishu,
    ask your xi basis guys to see the disk space of your xi system.........i think the log files of your xi system have consumed too much space on your xi system.... ask your basis guys to make some space available in your xi system then your this problem will be resolved.......
    Thanks,
    Rajeev Gupta

  • Creating new graphics object from a existing one and sending it for print

    Hello,
    i have a graphics object which is big in size, I am creating a new graphics object from the existing one as given below
    //map is a graphic object
    Graphic g1 = (Graphic)map.create(x,y,width,height);
    Graphic g2 = (Graphic)map.create(x,y,width1,height1);
    Graphic g3 = (Graphic)map.create(x,y,width2,height2);
    arrayList.add(g1);
    arrayList.add(g2);
    arrayList.add(g3);
    Now I want to send the graphic object g1,g2,g3 for print in the method
    public int print (Graphics g, PageFormat pf, int idx) throws PrinterException {
    // Printable's method implementation
    if (curPageFormat != pf) {
    curPageFormat = pf;
    pages = repaginate (pf);
    if (idx >= 3)) {
    return Printable.NO_SUCH_PAGE;
    g = (Graphics) arrayList.get(idx);
    return Printable.PAGE_EXISTS;
    This is not working... what is wrong. can anybody suggest..
    I tried standardprint.java to print a object inside a scrollpane, it is not printing the entire diagram. so I am thinking of something like this.... Please let me know what to do....
    Thanks
    Serj

    The easy way to do this is create a copy using Windows Explorer.
    Open the project and go to File > Rename.
    Then you have your 2013 ready made project.
    See www.grainge.org for RoboHelp and Authoring tips
    @petergrainge

  • Problem with decimal data visualization in a circular graphic object type

    When we are design a report using Crystal Reports 2008 we found the following problem. When we insert an object of type circle graphic selecting the option in the graphics wizard for view in the legend data both in value and percentage (u2018bothu2019 design) we cant show them in a two decimals format at the same time.
    Using the option u2018number formatu2019 and indicating two decimals only affects the value but not the percentage.
    Show both the value and the percentage with two decimals at same time itu2019s a necessary requirement for our report design.
    Is there any way to show both the value and the percentage in a circle graphic object with two decimals at the same time?
    Thanks.

    hello Jose,
    i am not sure what you mean by "circular graphic object type".
    there's nothing in the standard cr 2008 build that has this that i've ever found that creates a circle other than inserting a box and changing the rounding on the corners. if you're using a 3rd party product or add-on you'll need to contact whoever built it.
    cheers,
    jamie

  • Best way to draw thousands of graphic objects on the screen

    Hello everybody, I'm wanting to develop a game where at times thousands of graphic objects are displayed on-screen. What better way to do this in terms of performance and speed?
    I have some options below. Do not know if the best way is included in these options.
    1 - Each graphical object is displayed on a MovieClip or Sprite.
    2 - There is a Bitmap that represents the game screen. All graphical objects that are displayed on screen have your images stored in BitmapData. Then the Bitmap that represents the game screen copies for themselves the BitmapData of graphical objects to be screened, using for this bitmapData.copyPixels (...) or BitmapData.draw  (...). The Bitmap that represents the screen is added to the stage via addChild (...).
    3 - The graphical objects that are displayed on screen will have their images drawn directly on stage or in a MovieClip/Sprite added to this stage by addChild (...). These objects are drawn using the methods of the Graphics class, as beginBitmapFill and beginFill.
    Recalling that the best way probably is not one of these 3 above.
    I really need this information to proceed with the creation of my game.
    Please do not be bothered with my English because I'm using Google translator.
    Thank you in advance any help.

    Thanks for the information kglad. =)
    Yes, my game will have many objects similar in appearance.
    Some other objects will use the same image stored, just in time to render these objects is that some effects (such as changing the colors) will be applied in different ways. But the picture for them all is the same.
    Using the second option, ie, BitmapDatas, which of these two methods would be more efficient? copyPixels or draw?
    Thank you in advance any help. =D

  • Image in a Graphics object

    Hi, I'm dealing with the Batik API for working with svg images, but I need to do some wmf imager representation too.
    This API offers a class which is able to read WMF files, giving a "WMFRecordStore", that you can use to initialize a "WMFPainter".
    Anyway, this WMFPainter class has a "paint" method which I hoped that I could use to print the wmf info in the screen but... I don't know if it can be done.
    You must pass a Graphics object to the "paint" method.
    If I want to add an image to a JLabel, as I'd do with an ImageIcon, do I have to get the current JLabel Graphics object? Will the image keep displayed when repainting? Is this a correct way of doing this?
    thanks a lot

    if you have to paint special things on a component, you have to subclass the component and override the paint (or paintComponent) method. You don't want to be getting the graphics object from a component and draw on it, it's not going to work properly.

  • How to use a Graphics Object in a JSP?

    Hello, I do not know if this is a good or a silly question. Can anyone tell me if we can use a Graphics object in a JSP. For example to draw a line or other graphics, i am planning to use the JSP. Any help is much appreciated.
    Regards,
    Navin Pathuru.

    Hi Rob or Jennifer, could you pour some light here.
    I have not done a lot of research for this, but what i want to do is below the polygon i would like to display another image object like a chart... is it possible? If so how to do it? Any help is much appreciated.
    here is the code:
    <%
    // Create image
    int width=200, height=200;
    BufferedImage image = new BufferedImage(width,
    height, BufferedImage.TYPE_INT_RGB);
    // Get drawing context
    Graphics g = image.getGraphics();
    // Fill background
    g.setColor(Color.white);
    g.fillRect(0, 0, width, height);
    // Create random polygon
    Polygon poly = new Polygon();
    Random random = new Random();
    for (int i=0; i < 5; i++) {
    poly.addPoint(random.nextInt(width),
    random.nextInt(height));
    // Fill polygon
    g.setColor(Color.cyan);
    g.fillPolygon(poly);
    // Dispose context
    g.dispose();
    // Send back image
    ServletOutputStream sos = response.getOutputStream();
    JPEGImageEncoder encoder =
    JPEGCodec.createJPEGEncoder(sos);
    encoder.encode(image);
    %>
    Regards,
    Navin Pathuru

  • Need a Graphic Object for printing

    Hi,
    I generate a report with data from a database.
    At the moment I have an object that implements printable.
    Everytime the print method is called the report has
    to be created new.
    Now I want a seperate Graphics2D object in which teh report
    is created for once. And when a print
    job is started I want to copy it to the Graphics object
    in the printmethod.
    How can I create a Graphics2D Object for my own ?
    Thanx Stephan

    try:
    BufferedImage bufferedImage = new BufferedImage(500, 200, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = (Graphics2D) bufferedImage.getGraphics();
    g.drawString("Go to town!", 10, 10);This is how I did it when I needed to create images in a servlet. I expect it would also work for printing purposes... I guess I'll find out soon enough. :)

  • How does one Float a Graphic Object with Text? (Don't want the Graphics Frame stationary)

    I now know just enough InDesign to be dangerous.  So, help me from blowing myself up.
    SITUATION:
    I desire a Callout/Quote Box to emphase a quote--to separate it from the flowing text of the manuscript.  So, I created a curved-edge rectangle (graphic object) to make the "box", then filled it with the quoted text).  All was well in the land of Adobe Novice UNTIL I deleted some text above the newly-created graphic box/quote box.  I need the graphic to flow with (stay embedded in; hold its position in) the text outside the manuscript, not say anchored to page.
    QUESTION:
    Is there a way to have a graphic object which is placed in a manuscript flow with the manuscript text, so that it "holds its position" relative to the text.  For example, if I delete a paragraph of text above the graphic object, I want the graphic object to adjust accordingly.
    ASIDE:
    I am open to any other tricks or methods others use to insert callout or quote-boxes within the flowing text of a manuscript/book.
    Thanks in advance.

    Create your callout. If you will use it often, you can actually grab it and drag it to the desktop for reuse in any Document; it becomes an InDesign Snippet (.inds).
    Copy the callout graphic, insert your text curser into the text frame where you want the callout. You've just Anchored an Object.
    This is where you want to read up on Anchored Objects. You can highlight and baseline shift the callout (often necessay for anchored objects) , change leading, apply text wrap with standoff (you would select it with the selection tool for this), all of which are way beyond what I have ever tried, but managed it in less than 3 minutes. Basically treat it as a selection of type. The challenges will be line breaks, keep with, gosh knows.
    Bob mentioned CS5.5 has more friendly features, which I am not familiar with, and are beyond quick replies.
    Work through the above at your discretion, ask more DIRECT questions as needed, and you will get help. 

  • I cant get it to work! NullPointerExeption at first awt.Graphics Object

    I am writing a game with AWT having it as an applet. I intend NOT to use anything outside of Java 1.1
    For my Game i thought that i ATLEAST need the following classes:
    MainGame, Level, Unit.
    I Started writing Level. wrote a fewe methods for it such as
    drawGras(int grastype) And started to write MainGame to see if they would work together. it's is/is going to be my first Java application where i actually know what object orienting is... I have already wrote a game in Java but with out knowing what a class or what object orienting realy is(the game works rather good to) but this time i wanted to use object orienting but came up with problems =( if first posted in "New to Javaprogramming" but they couldn't help me and advice me here
    My previous post: http://forum.java.sun.com/thread.jsp?forum=54&thread=290558
    Here's my code:
    import java.awt.*;
    public class MainGame extends java.applet.Applet
         implements Runnable {
         Thread runner;
         Image ImgLevel, ImgUnit;
         public MainGame() {
              Level nr1 = new Level();
              nr1.init();
              nr1.setGround(300);
              nr1.drawGras(1);
              nr1.CalcGraphics();
              nr1.drawSky(1);
              Image ImgLevel = nr1.getLevelImage();
         public void paint(Graphics g) {
              g.drawImage(ImgLevel,0,0,this);
         public void update(Graphics g) {
              paint(g);
         public void init() {
              MainGame Game = new MainGame();
         public void stop() {
              runner = null;
              System.exit(1);
         public void start() {
              if(runner == null) {
                   runner = new Thread(this);
                   runner.start();
         void Pause(int time) {
             try {
                 Thread.sleep(time);
             } catch(InterruptedException e) {
               System.out.println(e.toString());
         public void run() {
              Thread thisThread = Thread.currentThread();
                   while(thisThread == runner) {
    class Level extends java.applet.Applet {
        Font BigText = new Font("Arial", Font.PLAIN, 36);
        Font Normal = new Font("Arial", Font.PLAIN, 14);
        Font Bold = new Font("Arial", Font.BOLD, 14);
        Graphics GrLevel;
        int pattern, sky, GroundtoWalk, Ground;
        Color BgColor = new Color(166,202,240);
        Color gras1 = new Color(0,255,0);
        Color gras2 = new Color(0,200,0);
        Color gras3 = new Color(0,100,0);
        Image ImgLevel;
        void setBgColor(int r, int g, int b) {
            BgColor = new Color(r,g,b);
        void CalcGraphics() {
            ImgLevel = createImage(800,600);
            GrLevel = ImgLevel.getGraphics();
        void setGround(int GrounD) {
            Ground = GrounD;
        void GroundToWalkADD(int addToGround) {
            GroundtoWalk = Ground + addToGround;
        void setGroundToWalk(int GrToWalk) {
            GroundtoWalk = GrToWalk;
        public void init() {
              System.out.println("Init 1"); // This was placed here when i was checking how far it got when debuging
              CalcGraphics();
              System.out.println("Init 2");
              drawGras(1);
              System.out.println("Init 3");
              repaint();
              System.out.println("Init 4");
        Image getLevelImage() {
            return ImgLevel;
        public void paint(Graphics g) {
              g.drawImage(ImgLevel,0,0,this);
        public void update(Graphics g) {
            paint(g);
        void drawGras(int pt) {
         GrLevel.setColor(BgColor);
         GrLevel.fillRect(0,0,800,600);
         switch(pt) {
              case 1:
                   GrLevel.setColor(gras1);
                   GrLevel.fillRect(0,GroundtoWalk,800,300);
                   GrLevel.setClip(0,GroundtoWalk,800,300);
                   for(int i = 0; 890>i;i=i+5) {
                        GrLevel.setColor(gras2);
                        GrLevel.drawLine(0+i,GroundtoWalk,-190+i,GroundtoWalk+300);
                   for(int i=950; 0<i; i=i-5) {
                        GrLevel.setColor(gras3);
                        GrLevel.drawLine(890-i,GroundtoWalk,1000-i,GroundtoWalk+300);
              break;
              case 2:
                   GrLevel.setColor(gras2);
                   GrLevel.fillRect(0,GroundtoWalk+5,800,300);
                   for(int i = 0; 890>i;i=i+5) {
                        GrLevel.setColor(gras3);
                        GrLevel.drawLine(0+i,GroundtoWalk,-190+i,GroundtoWalk+300);
                   for(int i=950; 0<i; i=i-5) {
                        GrLevel.setColor(gras1);
                        GrLevel.drawLine(890-i,GroundtoWalk,1000-i,GroundtoWalk+300);
              break;
              case 3:
                   GrLevel.setColor(gras3);
                   GrLevel.fillRect(0,GroundtoWalk+10,800,300);
                   for(int i = 0; 800>i; i=i+20) {
                        GrLevel.fillArc(0+i,GroundtoWalk,20,20,180,-180);
              break;
         pattern = pt;
        int getGrasPattern() {
             return pattern;
        void drawSky(int cl) {
                GrLevel.setColor(BgColor);
                GrLevel.fillRect(0,0,800,155);
                switch(cl) {
                    case 1:
                   for(int y = 0;y<7;y++) {
                   for(int x = 0;x<800;x=x+20) {
                                GrLevel.setColor(Color.white);
                                GrLevel.drawArc(x,y*20,20,20,180,180);
                                GrLevel.setColor(Color.red);
                                GrLevel.drawArc(x,y*20+4,20,20,180,180);
                                GrLevel.setColor(Color.yellow);
                                GrLevel.drawArc(x,y*20+2,20,20,180,180);
                                GrLevel.setColor(Color.green);
                                GrLevel.drawArc(x,y*20+8,20,20,180,180);
                                GrLevel.setColor(Color.blue);
                                GrLevel.drawArc(x,y*20+12,20,20,180,180);
                                GrLevel.setColor(Color.pink);
                                GrLevel.drawArc(x,y*20+16,20,20,180,180);
              break;
              case 2:
                        GrLevel.setColor(Color.gray);
              break;
         sky = cl;
         GrLevel.setFont(BigText);
         GrLevel.setColor(Color.black);
         GrLevel.fillRect(0,0,800,50);
         GrLevel.setColor(Color.white);
         GrLevel.drawString("Score Tabel - comming someday",((size().width)/2)-260, 40);
        int getSkyTyp() {
             return sky;
    }I tested running the code of class Level by puting it into Level.java and compiled it...ran it with appletviewer and it worked as it was intended to.
    But when i compiled it with MainGame... and in the HTML started MainGame.class,.....applet didn't intializeand i got the following error messege:
    Init 1
    java.lang.NullPointerException
            at Level.CalcGraphics(MainGame.java:84)
            at MainGame.<init>(MainGame.java:11)Line 82: void CalcGraphics() {
    Line 83: ImgLevel = createImage(800,600);
    Line 84: GrLevel = ImgLevel.getGraphics(); // The First awt.Graphics object
    Line 85: }
    Line 9:      public MainGame() {
    Line 10:     Level nr1 = new Level();
    Line 11:     nr1.CalcGraphics(); // calling the method above -> same error first awt.Graphics Object.
    If i change it os that "drawGras" comes first it's first awt.Graphics Line will show the same error
    Hope some one can and will help me

    As per the documentation of
    java.awt.Component.createImage(int,int):
    Creates an off-screen drawable image to be used for
    double buffering.
    Parameters:
    width - the specified width
    height - the specified height
    Returns:
    an off-screen drawable image, which can be used for
    double buffering. The return value may be null if the
    component is not displayable. This will always happen
    if GraphicsEnvironment.isHeadless() returns true.
    Since:
    JDK1.0 its not
    ImgLevel = createImage(800,600); that's making the problem but The first awt.Graphics Object in class Level, no mather which on it is =((
    >
    The key part is '...may be null if the component is
    not displayable.'
    You should put your graphics initialization code in
    start(), which will be called when your applet is
    ready to go. Before then, your applet is not
    displayable. (Also, remember to dispose() your
    graphics in your stop() method, if not sooner.)for the part writen above...I'll try to change it like you are saying.
    Thanx for your help!

  • Is there a way to initialize a Graphics object (indirectly)?

    Hi,
    I've a problem with Graphics Abstract class;
    how must I do to initialize a Graphics object?
    I must execute this code:
    Graphics gr;
    gr.drawString("Image",30,0);
    gr.drawString("not",30,30);
    gr.drawString("Found",30,60);
    image.paintIcon(null,gr,0,0);
    the compiler returns my the error:
    "gr not initialized"
    How can I do to initialize this last?
    Thank.

    Infact with
    gr=null;
    i've a null pointer exception;
    but I've also try
    jLabel2.setText("Prova");
    Graphics gr = jLabel2.getGraphics();
    gr.drawString("Image",30,0);
    gr.drawString("not",30,30);
    gr.drawString("Found",30,60);
    image.paintIcon(this,gr,0,0);
    jLabel3.setIcon(image);
    and I've always a null pointer exception.
    Why?
    Thank.

Maybe you are looking for