Null Graphics objects

Hello, I am attempting to write a java program that places a graph within a panel that the user can interact with. I have chosen Canvas() as the method to acieve this, but am running into problems with the instantiation of the graphics object- it keeps returning null, and I haven't the faitest idea why. Here is my code in question:
Canvas canvas = new Canvas();
Graphics g = canvas.getGraphics();
'g' is null- when I try to call g.drawLine(), it gives me a nullPointerException. Any help or information about why this is occuring would be greatly appreciated.

Well, I figured out that I needed to add the canvas to the contentPane before it had a Graphics object associated with it. But now, where the canvas is, there is a just a gray box. SetColor doesn't work, drawLine doesn't work, nothing. Here is the code:
Canvas canvas = new Canvas();
contentPane.add(canvas, BorderLayout.WEST);
show();
Graphics g = canvas.getGraphics();
Color white = new Color (255,255,255);
g.setColor(white);
setSize(300,200);
//Sets up the graph lines and tic marks
int size = 100;
g.drawLine(0, 0, size, 0);
g.drawLine(0, 0, 0, size);
//Horizontal tics
g.drawLine((size/4), 0, (size/4), (size/10));
g.drawLine((size/2), 0, (size/2), (size/10));
g.drawLine(((3*size)/4), 0, ((3*size)/4), (size/10));
g.drawLine(size, 0, size, (size/10));
//Vertical tics
g.drawLine(0, (size/4), (size/10), (size/4));
g.drawLine(0, (size/2), (size/10), (size/2));
g.drawLine(0, ((3*size)/4), (size/10), ((3*size)/4));
g.drawLine(0, size, (size/10), size);
show();
As I said, it compiles and runs fine, but there are no lines set up. I even added a bunch of show() statements as a desperate effort to get something to show up. Can anyone help? Thanks
I hate programming.

Similar Messages

  • In paintImmediately null graphics

    This message comes from the _paintImmediately method of JComponent but I'm not sure of the cause.  I don't see any exception stack trace and so I can only assume that SwingGraphics.createSwingGraphics(Graphics g) is returning a null Graphics object even though the Graphics object passed in is non-null.
    Any ideas? Anyone? Bueller? Bueller?

    Okay managed to stop my program throwing this error. For some reason I had a revalidate() in the middle of my processing code and not on the Event Thread. Still unsure as to why it only was an issue only on the second call but there we go.
    Thanks

  • 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();
    }

  • 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.

  • How must I initialize a graphics object?

    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.

    Or you can call getGraphics() on any Component, but most likely you will do any graphics in the paint method as tjacobs said.

  • How can I tell if a Graphics object has been disposed

    Any ideas?
    Thanks

    My goal is to find out if a graphics object has been disposed or not...
    ...but I'll play along. the application offers the user some nice graphics to amuse them, I use the Graphics object. In my endeavours, something isn't getting displayed where I expect it to, and I suspect that somewhere I'm accidentally disposing the graphics object. So, like checking for nulls, I want to debug the application and make sure the graphics context is as I expect.
    A bit of a side note, SWT will throw an exception if you try and use a "graphics" type object that has been disposed and has a method called, unsurprisingly enough, isDisposed(). Can you guess what it returns?

  • Accessing graphics object?

    Hi,
    I was wondering, is the only place the graphics object relevent inside the paintComponent method?
    I'm asking because I have a method that draws a custom progress bar. I have another method that draws that progress bar filling up over a arbitrary period of time. I want to use Thread.sleep() to provide a delay between redraws.
    Now I have the first method inside the paintComponent() method of a JPanel. Thats fine, works great! Now I didn't want to put the redraw method inside the paintComponent because the Thread delay will manifest itself in the painting of the component. So I thought I could solve this by making the second method a public one and using the getGraphics() method of the JPanel call the method once the object is instantiated. However this gives me a NullPointerException as soon as the method calls on the graphics object. Any ideas where I'm going wrong? Thanks!
    Method inside extended JPanel object
    public void testRun(Graphics g)
            // Cast to Graphics2D
            Graphics2D g2 = (Graphics2D)g;
            while(percentComplete < 100)
                try {
                    Thread.sleep(30);
                } catch (java.lang.InterruptedException ie) {
                    System.err.println("We got a problem");
                drawProgressBar(g2,percentComplete);
                percentComplete += 1;+
    +        }+
    +        percentComplete+ = 1;
            drawProgressBar(g2,percentComplete); // contains a repaint() method call to object
        }This inside the method of another object
    private void setupContentPanel()
            cpb = new CustomProgressBar();
            mainWindow.add(pb, BorderLayout.CENTER);
            cpb.testRun( pb.getGraphics() );
        }

    No, don't use update(...), that's not at all what the method is for. Also, avoid getGraphics() like the plague.
    What you need to do is increment an instance field using a Swing Timer, and invoke repaint(). The paintComponent override should use the current value of the instance field for appropriate painting. Example:import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    public class PseudoProgressBar {
       int progress = 0;
       JPanel panel= new JPanel() {
             @Override
             protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.setColor(Color.BLUE);
                int w = getWidth();
                int h = getHeight();
                g.fillRect(0, h/2-10, (w * progress)/100, 20);
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             @Override
             public void run() {
                new PseudoProgressBar().makeUI();
       public void makeUI() {
          JFrame frame = new JFrame();
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setSize(400, 100);
          frame.setContentPane(panel);
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
          new Timer(100, new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                progress %= 100;
                progress++;
                panel.repaint();
          }).start();
    }db

  • Getting the image of a graphics object?

    Hi,
    I have a graphics object that I want to update on a thread, but i don't want to redraw everything I had on each time I update (I only want to draw new items). in my paintComponent function, I have
    public void paintComponent(Graphics g)
              Graphics2D g2 = (Graphics2D)g;
              if (bufferedImage == null)
                   bufferedImage = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
              g2.drawImage(bufferedImage, 0, 0, null);
              drawBackground(g2);
              addItem(g2);
                 g2_ = g2;
         }where drawBackground makes the constant background and addItem draws new points. The problem that I'm having is that it is only drawing new items on the graph and not adding on to the existing image. I think this is because I never set bufferedImage to the current image, but I'm not sure how to do this?
    Thanks

    demo:
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.*;
    @SuppressWarnings("serial") public class Example extends JComponent {
        private BufferedImage buffer;
            setOpaque(true);
        @Override protected void paintComponent(Graphics g) {
            int w = getWidth(), h = getHeight();
            if (buffer == null ||
                w > buffer.getWidth() || h > buffer.getHeight()) {
                buffer = getGraphicsConfiguration().createCompatibleImage(w, h);
                composeBuffer();
            g.drawImage(buffer, 0, 0, null);
        protected void composeBuffer() {
            Graphics2D g2 = buffer.createGraphics();
            g2.setColor(Color.RED);
            g2.drawLine(0, 0, buffer.getWidth(), buffer.getHeight());
            g2.dispose();
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable(){
                public void run() {
                    JComponent comp = new Example();
                    comp.setPreferredSize(new Dimension(400,300));
                    JFrame f = new JFrame();
                    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    f.add(comp);
                    f.pack();
                    f.setLocationRelativeTo(null);
                    f.setVisible(true);
    }

  • How to make a Graphics2D object from a Graphics object?

    Hallo !
    Graphics g = pj.getGraphics();
    Graphics2D g2 = (Graphics2D) g;I get an Exception as follows:
    java.lang.ClassCastException: sun.awt.windows.WPrintGraphicsWrapper
    Is there an other possibility to to make a Graphics2D Object ? Or can I repair the error on an other way?
    Thank you Wolfgang

    Yes JBuilder makes a reference to this line.
    pj is a PrintJob.
    The only lines in this method for test are
    PrintJob pj = Toolkit.getDefaultToolkit().getPrintJob(p,"PrintWindow",null);
    Graphics g = pj.getGraphics();
    Graphics2D g2 = (Graphics2D) g;
    pj.end();Exception occurred during event dispatching:
    java.lang.ClassCastException: sun.awt.windows.WPrintGraphicsWrapper
    Wolfgang

  • Create a graphics object

    Hello,
    I want to create a graphics object. However, I need to use it in a function outside of a paint method in an applet.
    I need to create the object to check the FontMetrics of a combination of font parameters. This needs to be done independent of an applet. The problem is I want to use fontMetrics but not in an applet. I need to test the width and height of a message, which will eventually be used in an applet. However, this needs to be done before the applet receives the font.
    Can I create a graphics object outside of a paint method to check the fontMetrics of a combination of fonts? If not, can I check FontMetrics without a graphics object?

    Ok, by "graphic", when you say "I need to test whether one graphic will fit inside another", do you mean an instance of the Image class? If so (sorry, I thought you were wondering if you could create a "Graphics" object for use in calculating the Font Metrics) then you can use the stuff in the javax.imageio package to read your image, or, if you're not at 1.4 yet, do something like:
    image = new ImageIcon("image.gif").getImage();
    // Get the dimensions of the image; these will be non-negative
    width = image.getWidth(null);
    height = image.getHeight(null);to get the dimensions of your images.
    Hope that helped
    Lee

  • Cant do setColor(Color.BLACK); to a graphic object inside a class

    i have a graphic object inside a class:
    JPanel panel = new JPanel();
    Graphic lienzo = areadibujo.getGraphic();
    and then i cant do this:
    lienzo.setColor(Color.BLACK);
    netbeans error:
    <identifier> expected
    i just can do that inside a method from the class...

    HI i found the problem.
    The problem is that when i create the graphic object i do this:
    Graphics lienzo = areadibujo.getGraphics();
    areadibujo.getGraphics(); returns null so when i try to do something like lienzo.drawline(1,1,200,200); it just says nullpointer error, i guess at the time i create graphic object the panel "areadibujo" is not still created because the frame doesnt still shows, i can correct this by copying Graphics lienzo = areadibujo.getGraphics(); inside a actionperfmoded or other event method , but i dont wanna do that, where does the panel object already is created in constructor?.... i dont know if i explain my self well or how can i force areadibujo.getGraphics() to return something...

  • Draw to an image using graphics object

    ive been trying to this. create a starfield 800px wide and twice the height of the screen 2x600. this image would be scrolling down the screen giving the appearance of moving through space. what i did was create an image the called "starField", and created a graphics object "starFieldObj" to draw dots (stars) to this image.
    is this the correct way to do this? my program seems to work differently depending on where i call "generateStarField()" which draws to "starFieldObj"
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class Alpha1 extends Canvas implements Runnable, MouseMotionListener, MouseListener, KeyListener {
         private Image buffer; //bufer image
         private Graphics gfx;
         private Graphics starFieldObj;
         private Image playerShip;
         private int frames = 60; //frames per second
         private MediaTracker mediaTracker; //tracks loaded images
         private boolean ready; //ready to  start animation
         private int [] keys = new int[256];
         private int playerShipX = 100;
         private int playerShipY = 100;
         private static Random random = new Random();
         private Image starField;
         private int starFieldSpeed = 5;
         private int starFieldX = 0;
         private int starFieldY = -600;
         public static void main(String[] args)
              Alpha1 t = new Alpha1();
              Frame f = new Frame("blah");
              f.setSize(800, 600);
              f.add(t, BorderLayout.CENTER);
              f.show();
              t.start();
              t.requestFocus();
              f.addWindowListener(new WindowAdapter(){
                   public void windowClosing(WindowEvent e){
                        System.exit(0);}});
         public Alpha1()
              addKeyListener(this);
              addMouseListener(this);
              ready = false;
              mediaTracker = new MediaTracker(this);
              playerShip = getToolkit().getImage("testship1.png");
              //starField = getToolkit().getImage("testbg.png");
              //mediaTracker.addImage(playerShip, 0);
              mediaTracker.addImage(starField, 0);
              try {
                   mediaTracker.waitForID(0);
              catch (InterruptedException e) {
                   e.printStackTrace();
         public void start()
              buffer = createImage(getSize().width,getSize().height);
              //starField = createImage(getSize().width,getSize().height * 2);
              gfx = buffer.getGraphics();
              //starFieldObj = starField.getGraphics();
              generateStarfield();
              ready = true;
              new Thread(this).start();
         public void mouseDragged(MouseEvent e)     {}
         public void mouseMoved(MouseEvent e)     
              playerShipX = e.getX();
              playerShipY = e.getY();
         public void mouseReleased(MouseEvent e)     {}
         public void mousePressed(MouseEvent e)     {}
         public void mouseExited(MouseEvent e)     {}
         public void mouseEntered(MouseEvent e)  {}
         public void mouseClicked(MouseEvent e)     {}
         public void keyTyped(KeyEvent keyevent)     {}
         public void keyPressed(KeyEvent keyevent)
              keys[keyevent.getKeyCode()] = 1;
              System.out.println(keyevent.getKeyCode());
         public void keyReleased(KeyEvent keyevent)     
              keys[keyevent.getKeyCode()] = 0;
         public void run()
              while (true)
                   if (isVisible())
                        repaint();
                        updatePositions();
                   }//end if
                   try 
                   { Thread.sleep(1000/frames); }
                   catch (InterruptedException e)
                   { e.printStackTrace(); }
              }//end while
         public void paint(Graphics g) {     /*empty etc*/ }
         public void updatePositions()
              if (keys[38] == 1 & keys[40] == 0) //IF UP IS PRESSED
              { playerShipY -= 3; }
              if (keys[40] == 1 & keys[38] == 0) //IF DOWN IS PRESSED
              { playerShipY += 6; }
              if (keys[37] == 1 & keys[39] == 0) //IF LEFT IS PRESSED
              { playerShipX -= 5; }
              if (keys[39] == 1 & keys[37] == 0) //IF RIGHT IS PRESSED
              { playerShipX += 5; }
              //starFieldY = starFieldY + starFieldSpeed;
              //if (starFieldY == 0)
              //     starFieldY = -600;
              //     System.out.println("dadssa");
         public int getRandom(int from, int to)
              if (from > to)
                   int randTemp;
                   randTemp = from;
                   from = to;
                   to = randTemp;
              return random.nextInt(to-from+1)+from;
         public void generateStarfield()
              starFieldObj.setColor(Color.black);
              starFieldObj.fillRect (0, 0, 800, 600 * 2);
              for (int td=0; td < 900 ; td++) //draw 900x2 dots on 800x1200 image
                        starFieldObj.fillRect (getRandom(1,800), getRandom(1,600), 1, 1);
                        starFieldObj.fillRect (getRandom(1,800) + 800, getRandom(1,600) + 800, 1, 1);
         public void update(Graphics g)
              if (ready)
                   gfx.setColor(Color.black);
                   gfx.fillRect (0, 0, this.getSize().width, this.getSize().height);
                   //gfx.drawImage(starField,starFieldX,starFieldY,null);
                   gfx.drawImage(playerShip,playerShipX,playerShipY,null);
                   //gfx.drawString(Integer.toString(showFps),5,5);
                   g.drawImage(buffer,0,0,null);
    }

    updated code, i cant get starField to be 1200px in height
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class Alpha1 extends Canvas implements Runnable, MouseMotionListener, MouseListener, KeyListener {
         private Image buffer; //bufer image
         private Graphics gfx;
         private Graphics starFieldObj;
         private Image playerShip;
         private int frames = 60; //frames per second
         private MediaTracker mediaTracker; //tracks loaded images
         private boolean ready; //ready to  start animation
         private int [] keys = new int[256];
         private int playerShipX = 100;
         private int playerShipY = 100;
         private static Random random = new Random();
         private Image starField;
         private int starFieldSpeed = 5;
         private int starFieldX = 0;
         private int starFieldY = -600;
         public static void main(String[] args)
              Alpha1 t = new Alpha1();
              Frame f = new Frame("blah");
              f.setSize(800, 600);
              f.add(t, BorderLayout.CENTER);
              f.show();
              t.start();
              t.requestFocus();
              f.addWindowListener(new WindowAdapter(){
                   public void windowClosing(WindowEvent e){
                        System.exit(0);}});
         public Alpha1()
              addKeyListener(this);
              addMouseListener(this);
              ready = false;
              mediaTracker = new MediaTracker(this);
              playerShip = getToolkit().getImage("testship1.png");
              //starField = getToolkit().getImage("testbg.png");
              //mediaTracker.addImage(playerShip, 0);
              mediaTracker.addImage(starField, 0);
              try {
                   mediaTracker.waitForID(0);
              catch (InterruptedException e) {
                   e.printStackTrace();
         public void start()
              buffer = createImage(getSize().width,getSize().height);
              starField = createImage(getSize().width,1200);
              gfx = buffer.getGraphics();
              starFieldObj = starField.getGraphics();
              ready = true;
              new Thread(this).start();
         public void mouseDragged(MouseEvent e)     {}
         public void mouseMoved(MouseEvent e)     
              playerShipX = e.getX();
              playerShipY = e.getY();
         public void mouseReleased(MouseEvent e)     {}
         public void mousePressed(MouseEvent e)     {}
         public void mouseExited(MouseEvent e)     {}
         public void mouseEntered(MouseEvent e)  {}
         public void mouseClicked(MouseEvent e)     {}
         public void keyTyped(KeyEvent keyevent)     {}
         public void keyPressed(KeyEvent keyevent)
              keys[keyevent.getKeyCode()] = 1;
              System.out.println(keyevent.getKeyCode());
         public void keyReleased(KeyEvent keyevent)     
              keys[keyevent.getKeyCode()] = 0;
         public void run()
              generateStarfield();
              while (true)
                   if (isVisible())
                        repaint();
                        updatePositions();
                   }//end if
                   try 
                   { Thread.sleep(1000/frames); }
                   catch (InterruptedException e)
                   { e.printStackTrace(); }
              }//end while
         public void paint(Graphics g) {     /*empty etc*/ }
         public void updatePositions()
              if (keys[38] == 1 & keys[40] == 0) //IF UP IS PRESSED
              { playerShipY -= 3; }
              if (keys[40] == 1 & keys[38] == 0) //IF DOWN IS PRESSED
              { playerShipY += 6; }
              if (keys[37] == 1 & keys[39] == 0) //IF LEFT IS PRESSED
              { playerShipX -= 5; }
              if (keys[39] == 1 & keys[37] == 0) //IF RIGHT IS PRESSED
              { playerShipX += 5; }
              starFieldY = starFieldY + starFieldSpeed;
              if (starFieldY == 0)
                   starFieldY = -600;
                   System.out.println("dadssa");
         public int getRandom(int from, int to)
              if (from > to)
                   int randTemp;
                   randTemp = from;
                   from = to;
                   to = randTemp;
              return random.nextInt(to-from+1)+from;
         public void generateStarfield()
              starFieldObj.setColor(Color.black);
              starFieldObj.fillRect (0, 0, 800, 1200);
              for (int td=0; td < 900 ; td++) //draw 900x2 dots on 800x1200 image
                        starFieldObj.setColor(Color.white);
                        starFieldObj.fillRect (getRandom(1,800), getRandom(1,600), 1, 1);
                        starFieldObj.fillRect (getRandom(1,800) + 800, getRandom(1,600) + 800, 1, 1);
         public void update(Graphics g)
              if (ready)
                   gfx.setColor(Color.black);
                   //gfx.fillRect (0, 0, this.getSize().width, this.getSize().height);
                   gfx.drawImage(starField,starFieldX,starFieldY,null);
                   gfx.drawImage(playerShip,playerShipX,playerShipY,null);
                   //gfx.drawString(Integer.toString(showFps),5,5);
                   g.drawImage(buffer,0,0,null);
    }

  • Graphics object disappears

    Hi,
    My question is - why when I paint a graphics object (a java 2D object) onto a Frame , my graphics object appears on the screen for literally a split second and then disappears.
    How can I prevent this?
    Here's the code:
    public void paintSimple()
    Graphics h = null;
    show();
    h = this.getContentPane().getGraphics() ;
    Polygon p = new Polygon();
    p.addPoint(1,34);
    p.addPoint(23, 344);
    p.addPoint(234, 3);
    p.addPoint(12,42);
    h.setColor(Color.magenta);
    h.drawLine(1,222,333,44);
    this.getContentPane().update(h);
    Thanks,
    rpodolny

    Hi,
    Just a quick idea ...
    Your class possibly extends frame ...
    then overwrite the following:
    public void paint(Graphics g) {
    update(g);
    and ...
    public void update(Graphics g) {
    Graphics2D gd = (Graphics2D) g;
    Polygon p = new Polygon();
    p.addPoint(1,34);
    p.addPoint(23, 344);
    p.addPoint(234, 3);
    p.addPoint(12,42);
    gd.setColor(Color.magenta);
    gd.drawLine(1,222,333,44);
    //probably draw you Polygon somewhere ....
    I hope this is helping a bit. I think that the image is drawn and the over-drawn immediately after in the underlying methods. Now your drawing should be painted in every update so it should stay on the screen ...
    Hope this helps,
    Tim

  • Transparent Graphics Object

    Alright, I have one graphics object that draws all of the main elements of the screen, and I have a buffered image that is modified through a second graphics object. I want to know how to make the background for the second object transparent, so that if I drew something onto it, then drew the buffered image into the main graphics object, I'd be able to see all the drawing done in the original graphics object behind the uncovered areas, sort of like an overlay. Code examples are highly appreciated. Thanks in advance for any replies.
    (PS: Right now when I draw the image, it covers up the entire screen with the color grey, making it impossible to see the objects behind it.)

    I wrote example for AWT because in SWING it can be done very easy. Run this code, it runs fine. Use only your image files.
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Color;
    import java.awt.image.BufferedImage;
    import java.awt.*;
    import java.awt.event.*;
    public class ImageTest extends Canvas implements WindowListener {
    public static void main(String[] args) {
    Frame frame = new Frame("Image testing");
    ImageTest instance = new ImageTest();
    frame.add(instance);
    frame.addWindowListener(instance);
    frame.pack();
    frame.setVisible(true);
    public Dimension getPreferredSize() {
    return new Dimension(256, 256);
    BufferedImage backgroundImage;
    BufferedImage alphaImage;
    void initImage() {
    Image img = getToolkit().createImage("D:\\temp\\JavaTests\\viewcode.jpg");
    Image bkImage = getToolkit().createImage("D:\\temp\\JavaTests\\SolarEclipse.jpg");
    MediaTracker Mt = new MediaTracker(this);
    Mt.addImage(img, 0);
    Mt.addImage(bkImage, 1);
    try{
    Mt.waitForAll();
    }catch(Exception e){};
    BufferedImage bi = new BufferedImage(img.getWidth(this), img.getHeight(this), BufferedImage.TYPE_4BYTE_ABGR);
    alphaImage = new BufferedImage(bkImage.getWidth(this), bkImage.getHeight(this), BufferedImage.TYPE_4BYTE_ABGR);
    Graphics gr = bi.getGraphics();
    gr.drawImage(img, 0, 0, this);
    backgroundImage = (BufferedImage)bi;
    gr = alphaImage.getGraphics();
    gr.drawImage(bkImage, 0, 0, bkImage.getWidth(this)/2, bkImage.getHeight(this)/2, bkImage.getWidth(this)/2, bkImage.getHeight(this)/2, bkImage.getWidth(this), bkImage.getHeight(this), this);
    Color bl = new Color(0, 0, 0);
    for (int x=0; x<bkImage.getWidth(this); x++)
    for (int y=0; y<alphaImage.getHeight(this); y++) {
    Color c = new Color(alphaImage.getRGB(x,y));
    int r = c.getRed();//x*4;
    int g = c.getGreen();//y*4;
    int b = c.getBlue();//255 - (x+y)*2;//Math.abs(y*8-255);
    // Make transparent colors, which look like black
    int a = (r == b && g == b && r < 100 && g < 100 && b < 100)?0:255;
    int vv = (a<<24) | (r<<16) | (g<<8) | b;
    alphaImage.setRGB(x, y, vv);
    public void paint(Graphics gfx) {
    if (backgroundImage == null)
    initImage();
    gfx.drawImage(backgroundImage, 0, 0, this);
    int i = 0;
    int delta = 100;
    gfx.drawImage(alphaImage, i, i, this);
    gfx.drawImage(alphaImage, i + delta, i + delta, this);
    gfx.drawImage(alphaImage, i + delta*2, i + delta*2, this);
    gfx.drawImage(alphaImage, i + delta*3, i + delta*3, this);
    gfx.drawImage(alphaImage, i + delta*4, i + delta*4, this);
    gfx.drawImage(alphaImage, i + delta*5, i + delta*5, this);
    void exitForm(java.awt.event.WindowEvent evt) {
    System.exit(0);
    public void windowActivated(java.awt.event.WindowEvent windowEvent) {
    public void windowClosed(java.awt.event.WindowEvent windowEvent) {
    public void windowClosing(java.awt.event.WindowEvent windowEvent) {
    System.exit(0);
    public void windowDeactivated(java.awt.event.WindowEvent windowEvent) {
    public void windowDeiconified(java.awt.event.WindowEvent windowEvent) {
    public void windowIconified(java.awt.event.WindowEvent windowEvent) {
    public void windowOpened(java.awt.event.WindowEvent windowEvent) {

Maybe you are looking for

  • RFC Destination not getting connected - IDoc to XI scenario

    Hi Everybody, I want send an IDoc from R/3 System to Xi, I have created Two logical systems (Sender and Receiver correspondingly) and i have assigned the clients to them. Once i create RFC destination, i have specified all my technical settings as we

  • Italian tax reports - differences from SAP version 4.71 to 4.72

    Hi, Does anybody have the knowledge or documentation regarding the main differences between version 4.71 and version 4.72 from Insurance, regarding the Italian taxes report? Thanks Cristina

  • Error when creating project for ESS

    I am getting the folowing error when creating a project in Dev Studio for the ESS leave application ess~lea. Pls help Failed to sync DC "sap.com/ess/lea(sap.com_SAP_ESS_1)" in configuration "JDI_XSSTrack_D". File "C:\Documents and Settings\User\.dtc\

  • Socket.close() on both sides?

    Hello i'm creating a server-client application, but i came at a problem: i currently testing the logging out or disconnection. The protocol does this: client sends packet to server with request for logout, server pushes response back and ?closes sock

  • Time Machine index failures and external drives

    Greetings, I have been running into a number of failures with Time Machine on an Intel Core i7 iMac running Mac OS X 10.6.4. The external hard drive is an iOmega "eGo" 2 TB desktop drive connected with USB 2.0. I have used this kind of hard drive bef