Offscreen buffer in AWT/Java1.1

Hello, there!
I am programming on a browser-application that uses an AWT Scrollpane containing lots of elements, leading to heavy slow-downs and/or flickering (depends on the browser) when scrolling. My idea was to render the whole tree into an image and just paint this (as a normail Panel) instead of all the many single components. Of course this image needs to be updated when the tree changes.
Is it possible to do that in a way so that the single components inside the Panel still would react on mouse events?
I haven�t been able to try this out by myself, because I already had a problem with creating an offscreen-image. When I try to generate an Image from within a component with the createImage method, I receive a "null", not a new Image. I remeber that I had this problem already one year ago in another project and that it took some ugly work-arounds to get it work...
I guess I�m doing something wrong...
Can anyone help me? Thank you very much!
Znerole

I�ve been looking at some old sources of mine and I realized why the Image-creation didn�t work. I may not call the createImage-method from the components constructor!!!
Now I still don�t know if I may render a whole container into an Image with still having the single components reacting on mouseEntered and mouseExited... I think I have to try out on my own... :o

Similar Messages

  • Am I painting to an offscreen buffer correctly?

    Hi all,
    I am creating a simulation, and I want to paint the view for the simulation smoothly. Currently I have a thread that is looping around and calling repaint() every 50 ms. However, the animation is a little jerky and occasionally some parts of the view are visibly painted before others, so it looks odd (as a note, painting usually takes 30-40 ms, but occasionally spikes as high as 100 ms).
    I am trying out painting to an offscreen buffer first, but I'm not sure if I'm doing it the right way. I am using a short tutorial I found.
    I used to have a paint() method in my JComponent-extending view which used to look like:
    paint(Graphics g){
        // do a whole bunch of painting, including cycling through hundreds of
       // images and painting them to g
    }From what I could tell, I could keep this method intact, but instead of painting to the Graphics g that is passed in when repaint() is called, I could paint it to a BufferedImage, and then just paint that BufferedImage. I've posted the code below.
    However, when I try this, the painting is much, much jerkier then before. Basically it paints one half of the screen, then the other half, alternating at about a 10 hertz rate, so it's not good at all.
    Am I implementing the offscreen buffer pattern correctly? Would it not work in my case? Any suggestions? Thanks!
    The new code I used:
         private BufferedImage offImg;
          public void paint(Graphics g){
               if (getSize().width <= 0 || getSize().height <= 0)
                    return;
                  Graphics2D g2 = createGraphics2D(g);
                  draw(g2);
                  g2.dispose();
                  if (offImg != null && isShowing()) {
                    g.drawImage(offImg, 0, 0, this);
          public Graphics2D createGraphics2D(Graphics g){
              Graphics2D g2 = null;
              if (offImg == null || offImg.getWidth() != getSize().width
                      || offImg.getHeight() != getSize().height) {
                   offImg = (BufferedImage) createImage(getSize().width,
                           getSize().height);
              if (offImg != null) {
                   g2 = offImg.createGraphics();
                   g2.setBackground(getBackground());
              // .. set attributes ..
              g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                      RenderingHints.VALUE_ANTIALIAS_ON);
              // .. clear canvas ..
              g2.clearRect(0, 0, getSize().width, getSize().height);
              return g2;
         public void draw(Graphics g)
               // the exact same long complex code I originally had in the paint() method
           }

    except that he is using paintComponent instead of paintThat's actually a key difference. The double buffering magic that swing does starts in the JComponent's paint() method. If you override the paint() method to do your own thing, then there's a chance that you've effectively nullified double buffering for that component. That's why custom painting code goes into the the paintComponent method.
    Now, your combination of drawing to a BufferedImage and then drawing to the graphics context within the paintComponent method will+ be slower. The graphics context passed to
    public void paintComponent(Graphics g) {
    }will be to a VolatileImage 99.9% of the time. Which means you might as well directly use "g", since it's equivalent to drawing on a back image which happens to faster than BufferedImage. Drawing on an intermediate image within the paintComponent will only slow things down.
    In the event that you're painting too much and the animation is too slow, then the suggestion is to do all your drawings in a seperate thread on a back image, and then have your paintComponent(Graphics g) method paint only that image.
    public void paintComponent(Graphics g) {
        g.drawImage(theImage,0,0,null);
    }You would also decrease the sleep time in the seperate thread to try to get all the drawing done on time. You can use a BufferedImage for the back image, or with slightly more code managing - use a VolatileImage.
    Component#createVolatileImage(int width, int height);

  • Views using the same offscreen buffer, interfering with each other

    Hi all,
    I am creating an application where I display simulations. In order to keep the view of the simulation ticking along nicely, I paint the view to an offscreen buffer, and then paint the offscreen buffer to the screen.
    This has worked fine for me, so long as I was only viewing one single simulation on the screen at a time. I have now started displaying multiple simulations, and the views have started to interact with eachother -- one will paint over the other, particularly when I click or drag the simulation.
    I'm not using any static variables, so my guess is that the fault is the offscreen buffer that I'm using. I think my various views are using the same buffer. Is it possible that this is the problem?
    Here's how I paint my view:
    private BufferedImage offImg;
    private Graphics2D offG;
    public Graphics2D createGraphics2D(){
              if (offImg != null) {
                   offImg.flush();
                   offImg = null;
              RepaintManager repaintManager = RepaintManager.currentManager(this);
              try {
              offImg = (BufferedImage) repaintManager.getOffscreenBuffer(
                        this, this.getWidth(), this.getHeight());
              } catch (java.lang.NullPointerException e){
                   return null;
              offG = offImg.createGraphics();
              // .. clear canvas ..
              offG.clearRect(0, 0, getSize().width, getSize().height);
              return offG;
    private void draw() {
          if (offG == null)
                   createGraphics2D();
         offG.drawImage(...) //etc
    public void paintComponent(Graphics g){
               g.drawImage(offImg, 0, 0, this);
          }My first thought was to create a list of all the offImg's created and compare them. The different views are indeed getting the same image from repaintManager.getOffscreenBuffer, even though the component passed in as 'this' is different. The offG's created by each view are different, but since they belong to the same image, I assume it's the image that's important.
    Is this likely to be the source of my woes, and, assuming that I want to keep using the offscreen buffer (I do) is there a way around this problem?
    Thanks so much for any advice.

    Hello,
    I am creating an application where I display simulations. In order to keep the view of the simulation ticking along nicely, I paint the view to an offscreen buffer, and then paint the offscreen buffer to the screen.You may know that Swing uses double-buffering by default. So you usually don't really need to tweak Swing's own offscreen buffers.
    Painting conservatively on an applicative offscreen buffer is sounds (if painting is slow), but then your application has to create a dedicated offscreen buffer, not use Swing's ones.
    This has worked fine for me, so long as I was only viewing one single simulation on the screen at a time. I have now started displaying multiple simulations, and the views have started to interact with eachother -- one will paint over the other, particularly when I click or drag the simulation.
    I'm not using any static variables, so my guess is that the fault is the offscreen buffer that I'm using. I think my various views are using the same buffer. Is it possible that this is the problem?I can't tell for sure, but I'm not surprised if that's the case: all Swing ("lightweight") widgets within a same JFrame (or any other "heavyweight" top-level container) share the same native graphical resources, so presumably share the same offscreen buffer. It is Swing's machinery that arranges so that each widget paints onto a part of this buffer that corresponds to the widget's bounds.
              offImg = (BufferedImage) repaintManager.getOffscreenBuffer(
                        this, this.getWidth(), this.getHeight());You don't have to, and probably should not, ask Swing's RepaintManager for a buffer. You vould create a BufferedImage yourself, then draw onto it.
    offImg = new BufferedImage(...);Then your paintComponent method itself is fine:
    public void paintComponent(Graphics g){
               g.drawImage(offImg, 0, 0, this);
    Is this likely to be the source of my woes, and, assuming that I want to keep using the offscreen buffer (I do) is there a way around this problem?See above. And look for "offscreen graphics" on this forums, you'll probably find a lot of examples that do this way (and give example code, my sample above is sketchy and untested).
    Regards,
    J.
    Edited by: jduprez on Jun 2, 2011 12:10 AM
    Read this article if you need to kick the best out of your fast painting code (in particular, it mentions more informed ways than mine to create Image instances suitable for offscreen drawing):
    http://java.sun.com/products/java-media/2D/perf_graphics.html

  • How to double-buffer a JWindow?

    Hi,
    I made a resizable JWindow, but whenever I resize, J-components within the window flicker. (First setSize(), then validate() to redraw for correct sizes). I know JWindow is not double buffered, I want to override the paint() method to implement double buffering -- anyone knows how to do that? (...besides copying from JComponent.java)

    I think double buffering available in Swing with out you doing anything. Just add the following line to your window initialization.
    ((JPanel)window.getContentPane()).setDoubleBuffered(true);If this doesn't work, and I think it should. Then use the code below.
    This is code copied from http://java.sun.com/j2se/1.3/docs/guide/awt/designspec/lightweights.html
    The following is a Panel, but you can apply the same logic to JWindow.
    public class DoubleBufferPanel extends Panel {   
      Image offscreen;
       * null out the offscreen buffer as part of invalidation
      public void invalidate() {
          super.invalidate();
          offscreen = null;
       * override update to *not* erase the background before painting
      public void update(Graphics g) {
          paint(g);
       * paint children into an offscreen buffer, then blast entire image
       * at once.
      public void paint(Graphics g) {
          if(offscreen == null) {
             offscreen = createImage(getSize().width, getSize().height);
          Graphics og = offscreen.getGraphics();
          og.setClip(0,0,getSize().width, getSize().height);
          super.paint(og);
          g.drawImage(offscreen, 0, 0, null);
          og.dispose();

  • Speed of Swing versus double buffered AWT

    Hello
    I've noticed that drawing in a JPanel.paintComponent() takes about 4 times longer than drawing into an offscreen image in AWT Canvas.paint()
    Essential code excerpts follow
    // SWING, takes about 400 millis on my machine
    public void paintComponent(Graphics g) {
    g.setColor(Color.red);
    long startTime = System.currentTimeMillis();
    for (int i = 0; i < 10000; i++)
    g.draw3DRect((int) (Math.random() * 200), 20, 30, 40, true);
    long endTime = System.currentTimeMillis();
    System.out.println("paintComponent() took " + (endTime - startTime) + " millis");
    // AWT, takes about 100 millis on same machine
    public void paint(Graphics g) {
    if (offscreenGraphics == null || offscreenImage == null) {
    offscreenImage = createImage(getWidth(), getHeight());
    offscreenGraphics = offscreenImage.getGraphics();
    long startTime = System.currentTimeMillis();
    if (offscreenGraphics != null) {
    offscreenGraphics.setColor(Color.red);
    for (int i = 0; i < 10000; i++)
    offscreenGraphics.draw3DRect((int) (Math.random() * 200), 20, 30, 40, true);
    g.drawImage(offscreenImage, 0, 0, this);
    long endTime = System.currentTimeMillis();
    System.out.println("paint() took " + (endTime - startTime) + " millis");
    Note that I also tried drawLine() instead of draw3DRect() and experienced similar results
    Can someone explain why doing this in Swing is so slow?
    I'd hoped to take advantage of Swing's double buffering, but I ended up using the same old offscreen image technique in Swing.
    Nick Didkovsky

    Silly question, but did you turn on double buffering or extend a Swing component which has it on by default?
    Not all of them do.
    : jay

  • Sketch erased in AWT panel

    hai
    I have a very strange problem:
    I am presently working on drawiing a sketches on a panel using a PC tablet...
    the scenario is like this:- I have created a Frame and in that I have created a Panel , the screen coordinates of which are scynchronized to those of the PC tablet. At the bottom of the panel there is an OK button.
    Now as soon as I draw something on the tablet, I display it on the Panel.
    Now when I have completed drawing and when I press ok, I get a dialog box to display a message.
    what is the problem now is I see the dialog box, the sketch in the background i.e. on the Panel is erased.
    Can any one tell me what can be the problem with my interface......It will be extremely useful for me......thank you
    best wishes

    You're probably doing the painting in your MouseEventListeren?
    If so you have two ways to go, the easier one, and the one I would use, cause it's more "clean".
    The easier one is to use double-buffering (read about it on the http://java.sun.com) and do the painting in your EventListeren but do it on the offscreen-buffer, and just call repaint().
    The more difficult one is to build a model that holds all the data about the picture, that allows to reproduce it. In your case it would be probably just line coordinates plus colors. And in the EventListeren instead of doing all the painting, just add the new line to the model, and call repaint(). The actuall painting would be done in the paintComponent(Graphics g) method, where you should write a code that would paint your picture based on the data model.
    Hope it helps,
    Marcin

  • How come full screen exclusive mode is so slow?

    Hi. I am currently working on customer facing point-of-sale application. This application has a lot of animation going on and so needs quite speedy graphics performance. When I first investigated this it looked like I could do it in pure Java 2D which would be a lot easier than resorting to DirectX or OpenGL and mixing languages.
    Unfortunately as the app has moved closer to functional complete the graphics performance appears to have deteriorated to the point where it is unusable. So I have gone back to the beginning and written a test program to identify the problem .
    The tests I have done indicate that full screen exclusive mode runs about ten times slower than windowed mode. Which is mind boggling. Normally - say in DirectX - you would expect a full screen exclusive version of a games/graphics app to run a little bit quicker than a windowed version since it doesn't have to mess around with clip regions and moving vram pointers.
    My test program creates a 32 bit image and blits it to the screen a variable number of times in both windowed and full screen mode. Edited results look like this:
    iter wndw fscrn performance
         10 16.0 298.0 1862% slower
         20 47.0 610.0 1297% slower
         30 94.0 923.0 981% slower
         40 141.0 1205.0 854% slower
         50 157.0 1486.0 946% slower
         60 204.0 1877.0 920% slower
         70 234.0 2127.0 908% slower
         80 266.0 2425.0 911% slower
         90 297.0 2722.0 916% slower
         100 344.0 3253.0 945% slower
    The results are substantially the same with the openGL hint turned on (although I don't have that option on the release hardware). I am assuming that the images end up as managed since they are created through BufferedImage and the system is running under 1.5.
    Is there a way to get the full screen version running as fast as the windowed version?
    Here's the test prog:
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import javax.swing.JFrame;
    public class BlittingTest extends JFrame {
         BufferedImage     blankImage;
         BufferedImage     testImage;
         boolean               fullscreen;
         int                    frameNum;
         public BlittingTest( boolean fullscreen ) throws HeadlessException {
              super();
              // window setup. Escape to exit!
              addKeyListener ( new KeyAdapter() {
                   public void keyPressed( KeyEvent ke ) {
                        if (ke.getKeyCode() == KeyEvent.VK_ESCAPE ) {
                             System.exit(0);
              this.fullscreen=fullscreen;
              if ( fullscreen ) {
                   setUndecorated ( true );
              } else {
                   setTitle( "BlittingTest - <esc> to exit)");
                   setSize( 800, 600 );
              setVisible(true);
              setIgnoreRepaint(true);
              // strategy setup
              if ( fullscreen ) {
                   GraphicsDevice gdev =
                        GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
                   DisplayMode newDisplayMode = new DisplayMode (800, 600, 32,
                                                 DisplayMode.REFRESH_RATE_UNKNOWN);
                   DisplayMode oldDisplayMode = gdev.getDisplayMode();               
                   gdev.setFullScreenWindow(this);
                   gdev.setDisplayMode(newDisplayMode);
                   createBufferStrategy(2);
              // create assets
              testImage = new BufferedImage ( 50, 50, BufferedImage.TYPE_INT_ARGB );
              Graphics2D g = testImage.createGraphics();
              for ( int i = 0; i < 50; i ++ ) {
                   g.setColor( new Color ( 0, (50 - i) * 3, 0, i * 3 ));
                   g.drawLine( i, 0, i, 49 );
              g.dispose();
              blankImage = new BufferedImage ( 50, 50, BufferedImage.TYPE_INT_ARGB );
              g = blankImage.createGraphics();
              g.setColor ( Color.WHITE );
              g.fillRect( 0, 0, 50, 50 );
              g.dispose();
              frameNum = -1;
         public void init() {
              // blank both screen buffers
              for ( int i = 0; i < 2; i++ ) {
                   Graphics g2 = getBufferStrategy().getDrawGraphics();
                   g2.setColor ( Color.WHITE );
                   g2.fillRect( 0, 0, 800, 600 );
                   g2.dispose();
                   getBufferStrategy().show();
         public long testFrame ( int numBlits ) {
              int          x, y;
              long     timeIn, timeOut;
              frameNum++;
              Graphics g = getBufferStrategy().getDrawGraphics();
              g.drawImage( testImage, 0, 0, null );
              // blank previous draw
              if ( fullscreen ) {
                   if ( frameNum > 1 ) {
                        x = frameNum - 2;
                        y = frameNum - 2;
                        g.drawImage ( blankImage, x, y, null);
              } else {
                   if ( frameNum > 0 ) {
                        x = frameNum - 1;
                        y = frameNum - 1;
                        g.drawImage ( blankImage, x, y, null);                    
              x = (int) frameNum;
              y = (int) frameNum;
              timeIn = System.currentTimeMillis();
              for ( int i = 0; i < numBlits; i++ ) {
                   g.drawImage ( blankImage, x, y, null);
                   g.drawImage ( testImage, x, y, null);
              timeOut = System.currentTimeMillis();
              g.dispose();
              getBufferStrategy().show();
              return     timeOut - timeIn;
         public static void main(String[] args) {
              boolean error = false;
              BlittingTest window = null;
              double []     windowedTest = new double [101];
              double []     fullscreenTest = new double [101];
              window = new BlittingTest ( false );     
              window.init();
              for ( int f = 1; f <= 100; f++ ) {
                   windowedTest[f] = window.testFrame( f * 10 );
              window.setVisible(false);
              window.dispose();
              window = new BlittingTest ( true );     
              window.init();
              for ( int f = 1; f <= 100; f++ ) {
                   fullscreenTest[f] = window.testFrame( f * 10 );
              window.setVisible(false);
              window.dispose();
              for ( int f = 10; f <= 100; f++ ) {
                   System.out.println ( "\t" + f + "\t" + windowedTest[f] +
                             "\t" + fullscreenTest[f] +
                             "\t" + (int) ( (fullscreenTest[f]/windowedTest[f])*100.0) + "% slower");
    }

    Well I could do...
    The problem is that I am compositing multiple layers of alpha transparent images. If I just render straight to the screen I get nasty flicker where I see glimpses of the background before the top layer(s) get rendered. So I would have to render to an offscreen buffer and then blit the assembled image into the screen. Even then there will be some tearing as you can never sync to the screen refresh in windowed mode.
    And the thing is - there ought to be a 'proper' solution, g*dd*mm*t. Surely the core team didn't put together a solution that is ten times slower than it should be and then say 'What the heck, we'll release it anyway'.
    I mean, if you can't believe in Sun engineering what can you believe in?

  • Having a problem saving the graphics on a canvas.

    I'm having a problem saving graphics on a canvas. It draws on the canvas but when another window comes up the graphics disappear. I put in a method to take the graphics on the canvas and repaint it with the graphics. But this comes up blank. So I don't know why this is happening. It is probably the paint method but I don't know why. If anyone has any ideas could you please respond because I have had this problem for ages now and it's driving me mad and I have to get this finished or I'm going to be a lot of trouble. I'll show you the code for the class I am concerned with. It is long but most of it can be disregarded. The only parts which are relevent are the paint method and where the drawline e.t.c are called which is in the mouse release
    package com.project.CSSE4;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.ImageFilter;
    import java.awt.image.CropImageFilter;
    import java.awt.image.FilteredImageSource;
    import java.io.*;
    import java.util.*;
    import java.net.*;
    import javax.swing.*;
    import java.sql.*;
    public class CanvasOnly extends JPanel
           implements MouseListener, MouseMotionListener
       public static final int line = 1;
       public static final int freehand = 2;
       public static final int text = 3;
       public static final int mode_paint = 0;
       public static final int mode_xor = 1;
       public Color drawColor;
       public int drawThickness = 1;
       public int drawType = 0;
       public boolean fill = false;
       private boolean dragging = false;
       public int oldx = 0;
       public int oldy = 0;
       private int rectangleWidth;
       private int rectangleHeight;
       private tempLine draftLine;
       private tempText draftText;
       public Canvas pad;
       public static final Font defaultFont =
         new Font("Helvetica", Font.BOLD, 14);
       protected boolean floatingText = false;
       boolean showingPicture;
       protected Image offScreen;
       public JTextArea coor;
       public JButton writeIn;
       Connection connection;
       String codeLine;
       int x = 0;
       int y = 0;
       public CanvasOnly()
           try
                Class.forName("com.mysql.jdbc.Driver").newInstance();
           }catch( Exception e)
                 System.err.println("Unable to find and load driver");
                 System.exit(1);
            pad = new Canvas();
            pad.setBackground(Color.white);
            pad.setVisible(true);
            pad.setSize(400, 400);
           coor = new JTextArea(15, 15);
           writeIn = new JButton("load TExt");
           writeIn.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent event1)
                     try
                   Statement statement = connection.createStatement();
                   ResultSet rs = statement.executeQuery("SELECT * FROM submit WHERE file_name = 'cmd.java'");
                   rs.next();
                   String one1 = rs.getString("student_id");
                   //System.out.println("one1 :" + one1);
                   String two1 = rs.getString("file_name");
                   //System.out.println("two1 : " + two1);
                    InputStream textStream = rs.getAsciiStream("file");
                    BufferedReader textReader = new BufferedReader(
                                     new InputStreamReader(textStream));
                    codeLine = textReader.readLine();
                    x = 0;
                    y = -12;
                    while(codeLine != null)
                        y = y + 12;
                        //fileText.append( line + "\n");
                        //canvasPad.drawTheString(line, x, y);
                        drawText(Color.black, x, y, codeLine, mode_paint);
                        codeLine = textReader.readLine();
                     textReader.close();
                    pad.setSize(400, y);
                    Timestamp three1 = rs.getTimestamp("ts");
                    //System.out.println(three1);
                    textReader.close();
                    rs.close();
              }catch (SQLException e)
                System.err.println(e);
              catch(IOException ioX)
                System.err.println(ioX);
            //setSize(300,300);
            drawColor = Color.black;
            pad.addMouseListener(this);
         pad.addMouseMotionListener(this);
         offScreen = null;
       public Image getContents()
         // Returns the contents of the canvas as an Image.  Only returns
         // the portion which is actually showing on the screen
         // If the thing showing on the canvas is a picture, just send back
         // the picture
         if (showingPicture)
             return (offScreen);
         ImageFilter filter =
             new CropImageFilter(0, 0, getWidth(), getHeight());
         Image newImage =
             createImage(new FilteredImageSource(offScreen.getSource(),
                                  filter));
         return(newImage);
        public void setImage(Image theImage)
         // Fit it to the canvas
         offScreen = theImage;
         repaint();
         showingPicture = true;
        synchronized public void paint(Graphics g)
         int width = 0;
         int height = 0;
         //The images are stored on an off screen buffer.
            //offScreen is the image declared at top
         if (offScreen != null)
                  //intislise the widt and heigth depending on if showingpicture is true
              if (!showingPicture)
                       width = offScreen.getWidth(this);
                       height = offScreen.getHeight(this);
                   //width = getWidth(this);
                   //height = getHeight(this);  //offScreen
              else
                   //width = pad.getSize().width;
                   //height = getSize().height;
                   width = pad.getWidth();
                   //width = getSize().width;
                   height = pad.getHeight();
                   //height = getSize().height;
                    //Draws as much of the specified image as has already
                    //been scaled to fit inside the specified rectangle
                    //The "this" is An asynchronous update interface for receiving
                    //notifications about Image information as the Image is constructed
    //This is causing problems
              g.drawImage(offScreen, 0, 0, width, height, pad);
              g.dispose();
         //clear the canvas with this method
        synchronized public void clear()
         // The maximum size of the usable drawing canvas, for now, will be
         // 1024x768
         offScreen = createImage(1024, 768);
         //Creates an off-screen drawable image to be used for double buffering
         pad.setBackground(Color.white);
         //Set the showingPicture to false for paint method
         showingPicture = false;
         repaint();
         synchronized public void drawLine(Color color, int startx, int starty,
                              int endx, int endy, int thickness,
                              int mode)
         int dx, dy;
         Graphics g1 = pad.getGraphics();
         Graphics g2;
         //if image is not intialised to null
         //the getGraphics is used for freehand drawing
         //Image.getGraphics() is often used for double buffering by rendering
            //into an offscreen buffer.
         if (offScreen != null)
             g2 = offScreen.getGraphics();
         else
             g2 = g1;
            //mode is put into the method and XOR is final and equal to 1
         if (mode == this.mode_xor)
                  //calls the setXOR mode for g1 and g2
                  //Sets the paint mode of this graphics context to alternate
                    //between this graphics context's current color and the
                    //new specified color.
              g1.setXORMode(Color.white);//This will
              g2.setXORMode(Color.white);
         else
                  //Sets this graphics context's current color to the
                    //specified color
              g1.setColor(color);
              g2.setColor(color);
         if (endx > startx)
             dx = (endx - startx);
         else
             dx = (startx - endx);
         if (endy > starty)
             dy = (endy - starty);
         else
             dy = (starty - endy);
         if (dx >= dy)
              starty -= (thickness / 2);
              endy -= (thickness / 2);
         else
              startx -= (thickness / 2);
              endx -= (thickness / 2);
         for (int count = 0; count < thickness; count ++)
              g1.drawLine(startx, starty, endx, endy);
              g2.drawLine(startx, starty, endx, endy);
              if (dx >= dy)
                  { starty++; endy++; }
              else
                  { startx++; endx++; }
            //Disposes of this graphics context and releases any system
            //resources that it is using.
         g1.dispose();
         g2.dispose();
         //This method is not causing trouble
         synchronized public void drawText(Color color, int x, int y,
                String text, int mode)
         Graphics g1 = pad.getGraphics();
         Graphics g2;
         if (offScreen != null)
             g2 = offScreen.getGraphics();
         else
             g2 = g1;
         if (mode == this.mode_xor)
              g1.setXORMode(Color.white);
              g2.setXORMode(Color.white);
         else
              g1.setColor(color);
              g2.setColor(color);
         g1.setFont(new Font("Times Roman", Font.PLAIN, 10));
         g2.setFont(new Font("Times Roman", Font.PLAIN, 10));
         g1.drawString(text, x, y);
         g2.drawString(text, x, y);
         g1.dispose();
         g2.dispose();
          //connect to database
      public void connectToDB()
        try
           connection = DriverManager.getConnection(
           "jdbc:mysql://localhost/submissions?user=root&password=football");
                     //may have to load in a username and password
                                                     //code "?user=spider&password=spider"
        }catch(SQLException connectException)
           System.out.println("Unable to connect to db");
           System.exit(1);
      //use this method to instatiate connectToDB method
      public void init()
           connectToDB();
        protected void floatText(String text)
         draftText = new tempText(this.drawColor,
                            this.oldx,
                            this.oldy,
                                        text);
         this.floatingText = true;
        //nothing happens when the mouse is clicked
        public void mouseClicked(MouseEvent e)
        //When the mouse cursor enters the canvas make it the two
        //straigth lines type
        public void mouseEntered(MouseEvent e)
         pad.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
        //When mouse exits canvas set to default type
        public void mouseExited(MouseEvent E)
         pad.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        //used for creating the shapes and positioning thetext
        public void mousePressed(MouseEvent e)
             // Save the coordinates of the mouse being pressed
         oldx = e.getX();
         oldy = e.getY();
         // If we are doing lines, rectangles, or ovals, we will show
         // draft lines to suggest the final shape of the object
         //Draw type is a publc int which can be changed
         if (drawType == this.line)
            draftLine = new tempLine(drawColor, oldx, oldy, oldx,
                                 oldy, drawThickness);
            // Set the draw mode to XOR and draw it.
            drawLine(draftLine.color, draftLine.startx,
            draftLine.starty, draftLine.endx,
            draftLine.endy, drawThickness, this.mode_xor);
        //mouse listener for when the mouse button is released
        public void mouseReleased(MouseEvent e)
             if (drawType == this.line)
              // Erase the draft line
              drawLine(draftLine.color, draftLine.startx, draftLine.starty,
                    draftLine.endx, draftLine.endy, drawThickness,
                    this.mode_xor);
              // Add the real line to the canvas
              //When the imput changes to "mode_paint" it is drawen
              //on the canvas
              drawLine(drawColor, oldx, oldy, e.getX(), e.getY(),
                    drawThickness, this.mode_paint);
              dragging = false;
         else if (drawType == this.text)
              if (floatingText)
                   // The user wants to place the text (s)he created.
                   // Erase the old draft text
                   drawText(drawColor, draftText.x, draftText.y,
                                            draftText.text, this.mode_xor);
                       String str = Integer.toString(e.getX());
                       String str1  = Integer.toString(e.getY());
                       coor.append(str + " " + str1 + "\n");
                   // Set the new coordinates
                   draftText.x = e.getX();
                   draftText.y = e.getY();
                   // Draw the permanent text
                   drawText(drawColor, draftText.x, draftText.y,
                         draftText.text, this.mode_paint);
                   floatingText = false;
         public void mouseDragged(MouseEvent e)
            if (drawType == this.freehand)
              drawLine(drawColor, oldx, oldy, e.getX(), e.getY(),
                    drawThickness, this.mode_paint);
              oldx = e.getX();
              oldy = e.getY();
         else
             dragging = true;
         if (drawType == this.line)
            // Erase the old draft line
            drawLine(draftLine.color, draftLine.startx, draftLine.starty,
              draftLine.endx, draftLine.endy, drawThickness,
              this.mode_xor);
            // Draw the new draft line
            draftLine.endx = e.getX();
            draftLine.endy = e.getY();
            drawLine(draftLine.color, draftLine.startx, draftLine.starty,
              draftLine.endx, draftLine.endy, drawThickness,
              this.mode_xor);
         public void mouseMoved(MouseEvent e)
             if (floatingText)
              // When the user has entered some text to place on the
              // canvas, it remains sticky with the cursor until another
              // click is entered to place it.
              // Erase the old draft text
              drawText(drawColor, draftText.x, draftText.y,
                                draftText.text, this.mode_xor);
              // Set the new coordinates
              draftText.x = e.getX();
              draftText.y = e.getY();
              // Draw the new floating text
              drawText(drawColor, draftText.x, draftText.y,
                        draftText.text, this.mode_xor);
         //declare  a class for the line shown before the is as wanted
        class tempLine
         public Color color;
         public int startx;
         public int starty;
         public int endx;
         public int endy;
         public int thickness;
         public tempLine(Color mycolor, int mystartx, int mystarty,
                      int myendx, int myendy, int mythickness)
             color = mycolor;
             startx = mystartx;
             starty = mystarty;
             endx = myendx;
             endy = myendy;
             thickness = mythickness;
        class tempText
         public Color color;
         public int x;
         public int y;
         public String text;
         public tempText(Color mycolor, int myx, int myy, String mytext)
             color = mycolor;
             x = myx;
             y = myy;
             text = mytext;
    }

    http://www.java2s.com/ExampleCode/2D-Graphics/DemonstratingUseoftheImageIOLibrary.htm

  • Initial postion of image changed but now image does not move

    hi can any one solve this problem please, i have been trying to change the initial position of my image when i run it 1st on java textpad......
    i seem to have moved the initial position of the image by the following >
    public void paint(Graphics g) {
              g.drawImage(CurrentImage,xPos = 10,yPos = 100,this);but now the image does not move when i press the keys in its new position
    does anyone one know how to solve this?? if you do please reply THANK you.
    the original code is below >
    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.io.File;
    import java.io.IOException;
    import javax.sound.sampled.*;
    import javax.sound.midi.*;
    import javax.swing.*;
    import java.awt.Image.*;
    public class Man3 extends Applet implements KeyListener {
         int xPos, yPos;
         Image man1;
         Image man2;
         Image man3;
         Image man4;
         Image man5;
         Image man6;
         Image CurrentImage;
         Image offScreenBuffer;
         AudioClip tune;
         public void init() {
              setBackground(Color.white);
              xPos = this.getSize().width/2;
              yPos = this.getSize().height/2;
              man1 = getImage(getCodeBase(),"man1.gif"); // right hand up
              man2 = getImage(getCodeBase(),"man2.gif"); // straight
              man3 = getImage(getCodeBase(),"man3.gif"); // right hand down
              man4 = getImage(getCodeBase(),"man4.gif"); // left hand up
              man5 = getImage(getCodeBase(),"man5.gif"); // straight
              man6 = getImage(getCodeBase(),"man6.gif"); // left hand down
              CurrentImage = man2; // man facing right
              addKeyListener(this);
              requestFocus();
              tune = getAudioClip(getCodeBase(), "Track.wav");
         public void paint(Graphics g) {
              g.drawImage(CurrentImage,xPos,yPos,this);
         public  void checkXmin()
                   if (xPos == 0) xPos = 500;
         public  void checkXmax()
                   if (xPos == 500) xPos = 0;
         public void checkYmin()
                   if (yPos == 0) yPos = 350;
         public void checkYmax()
                   if (yPos == 350) yPos = 0;
         xPos+=1;
         if (xPos>500) xPos=0;
         if (xPos==0) tune.play();
         // man walks right
         public void checkCurrentImageRight()
                   if((CurrentImage == man6)||(CurrentImage == man5)||(CurrentImage == man4))
                        CurrentImage = man2;
                   if(CurrentImage == man3)          CurrentImage = man1;
                   else if (CurrentImage == man1)     CurrentImage = man3;
                   else if(CurrentImage == man2)     CurrentImage = man1;
         // man walks left
         public void checkCurrentImageLeft()
                   if((CurrentImage == man3)||(CurrentImage == man2)||(CurrentImage == man1))
                        CurrentImage = man5;
                   if(CurrentImage == man6)          CurrentImage = man4;
                   else if (CurrentImage == man4)     CurrentImage = man6;
                   else if(CurrentImage == man5)     CurrentImage = man4;
         public void keyPressed(KeyEvent evt) {
              int offset;
              int x = evt.getKeyCode();
              if (evt.isShiftDown()) {
                   offset = 20;
              else {
                   offset = 10;
              switch (x) {
                   case (KeyEvent.VK_UP):                     // man goes up
                             checkYmin();
                             //checkCurrentImage(2);
                             yPos -= offset;
                             break;
                   case (KeyEvent.VK_DOWN):
                             checkYmax();
                             //checkCurrentImage(2);          // man goes down
                             yPos += offset;
                             break;
                   case (KeyEvent.VK_LEFT):               // man walks left
                             checkXmin();
                             checkCurrentImageLeft();
                             xPos -= offset;
                             break;
                   case (KeyEvent.VK_RIGHT):               // man walks right
                             checkXmax();
                             checkCurrentImageRight();
                             xPos += offset;
                             break;
              repaint();  // display image
         public void keyTyped(KeyEvent evt) {
         public void keyReleased(KeyEvent evt) {
        public void update(Graphics g)
            // Will hold the graphics context from the offScreenBuffer.
            // We need to make sure we keep our offscreen buffer the same size
            // as the graphics context we're working with.
            if ((offScreenBuffer==null) || (offScreenBuffer.getWidth(this) != getWidth()) || (offScreenBuffer.getHeight(this) != getHeight()))
                xPos = getWidth()/2;
                yPos = getHeight()/2;
                offScreenBuffer = this.createImage(getWidth(), getHeight());
            // We need to use our buffer Image as a Graphics object:
            Graphics gr = offScreenBuffer.getGraphics();
            gr.setColor(getBackground());
            gr.fillRect(0, 0, getWidth(), getHeight());
            paint(gr); // Passes our off-screen buffer to our paint method, which,
            // unsuspecting, paints on it just as it would on the Graphics
            // passed by the browser or applet viewer.
            g.drawImage(offScreenBuffer, 0, 0, this);
            // And now we transfer the info in the buffer onto the
            // graphics context we got from the browser in one smooth
    }

    Not only is this your 7th or 8th posting on this topic, you can't even wait 15 minutes before bumping the posting.
    Your question is no more important than anyone elses on the forum and continually posting, starting new threads on the same topic is one sure way to get your posting ignored.

  • Accelerate swing graphics

    Hi All
    I'm currently working on a project that includes graphical representation using swing. I got some foreground-objects that move over a background. Unfortunately the performance is not as well as I expected. Perhaps there is a better approach for solving this problem:
    general idea:
    o) I use 3 images/grahics2d-objects of these images:
    one image contains the background picture
    one image contains the foreground picture
    one image is used as a offscreen buffer
    o) I draw the background picture over the offscreen buffer
    o) I draw the foreground picture also over the offscreen buffer
    o) Finally the offscreen buffer is written to the graphics-object
    the graphics are full-screen (1024x768). Is there a better way to do this?
    I would greatly appreciate any kind of help,
    exxion

    If its animation we talking about here. Use threads to do the animation calculation. But dont use too many threads, not wise to over use the power of threads.
    Try the code. Save it as japp.java. Fix the errors. Like image filenames. As i was rushing coding this.
    import java.awt.Graphics;
    import javax.swing.*;
    import java.awt.Image;
    class ImageBackgroundDraw extends Thread {
      JFrame app;
      int x;
      int y;
      public void setXY(int a, int b) {
        x = a;
        y = b;
      public drawImage(JFrame a, Image i) {
        this.app = a;
        x = 0;
        y = 0;
        start();
      public void run() {
        while (true) {
          // Update coordinates of image.
          // I dont know maybe x++;
          // Give it a little sleep we dont want it too fast
          if (x < app.w) x++
          try { sleep(app.sleep_duration); } catch (Exception e) { }
      public void paint(Graphics g) {
         Graphics2D g2 = (Graphics2D)g; 
         g2.drawImage(Image,x,y,app);
    public class japp extends javax.swing.JFrame implements Runnable {
        boolean initG = true;// Allow first Init of buffImgSurface
        private BufferedImage buffImg = null;
        private Graphics2D buffImgSurface;   
        private Thread appThread;
        public int w; // App height;
        public int h; // App width;
        ImageBackgroundDraw[] ibd = new ImageBackgroundDraw[2];
        Image back = new Image("back.gif");
        Image fore= new Image("fore.gif");
        long start = 0;             // Frame start time
        long tick_end_time;         // End frame time
        long tick_duration;         // Time taken to display the frame
        public long sleep_duration; // How long to sleep     
        static final int MIN_SLEEP_TIME = 10, // Min time to sleep for
                         MAX_FPS = 20,        // Max frame rate.  
                         MAX_MS_PER_FRAME=1000/MAX_FPS;// MS per frame
        float fps=0;  // Current frame rate
        public japp() {
          init();
          start();
        public void setWH(int a, int b) {
            w = a;
            h = b;
        public void init() {
          ibd[0] = new ImageBackgroundDraw(this,backgroundImage);
          ibd[1] = new ImageBackgroundDraw(this,ForgroundImage);
          ibd[3] = new ImageBackgroundDraw(this,ForgroundImage);
          ibd[0].setXY(0,0);
          ibd[1].setXY(0,0);
          ibd[1].setXY(0,0);
        public void update(Graphics g) {
          Graphics2D g2 = (Graphics2D)g; 
          // Erase graphics
          buffImgSurface.setBackground(Color.black);
          buffImgSurface.clearRect(0,0,w, h);
          for (int i=0; i < ibd.length; i++) {
            ibd.paint(buffImgSurface);
          g2.drawImage(buffImg,0,0,this);
        public void paint(Graphics g) {
          if (initG == true) {           
                buffImg = (BufferedImage)createImage(w,h);
                buffImgSurface = buffImg.createGraphics();   
                initG = false;
        public void start() {
            if (appThread == null) {
                appThread = new Thread(this, "app");
                appThread.start();
        public void run() {
          // While this thread is active and running keep repeating
          while (true) {
            start = System.currentTimeMillis();
            repaint();
            tick_end_time=System.currentTimeMillis();
            tick_duration=tick_end_time - start;
            if (sleep_duration < MIN_SLEEP_TIME) {
              sleep_duration=MIN_SLEEP_TIME;
            fps = 1000 / (sleep_duration + tick_duration);
    }If you like g.drawString("FPS"+fps,1,10); to show FPS to see if there is any improvement. Otherwise try JNI!(Java Native Interface) Coding and make up your own graphic routines for your applications. You can program your Java API in Assembly with JNI!.

  • Splash screen HELP!!!!

    I am trying to implement a splash screen but cannot get it to be displayed....and also how do I get ito appear for a certain before it being disposed.
    JWindow splash = new JWindow();
         JLabel image = new JLabel(new ImageIcon("images/splash.jpg"));
         splash.getContentPane().add(image, BorderLayout.CENTER);
         splash.setVisible(true);
    thanks
    siraj

    Hi!
    I post code of a splash screen I'm using. I expect it helps you:
    import java.awt.*;
    public class SplashWindow extends Window implements Runnable {
         private Thread runner;   
         private Image splashIm;   
         private StringBuffer Message;   
         private Image Buffer;   
         private Graphics gBuffer;   
         private int animationStep;
         private int width;
         private int height;
         public SplashWindow(Frame parent, Image splashIm) {       
              this(parent, 400, 222, splashIm);
         public SplashWindow(Frame parent, int width, int height, Image splashIm) {       
              super(parent);
              this.width = width;
              this.height = height;
              this.splashIm = splashIm;       
              setSize(width,height);
              animationStep = 0;       
              /* Center the window */       
              Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize();       
              Rectangle winDim = getBounds();       
              setLocation((screenDim.width - winDim.width) / 2, (screenDim.height - winDim.height) / 2);
              setVisible(true);       
              toFront();       
              start();   
         //Used for flicker-free offscreen drawing   
         public void addNotify() {       
              super.addNotify();       
              Buffer = createImage(width, height);
              gBuffer = Buffer.getGraphics();   
         public void buildBuffer() {     
              if (splashIm != null) {       
                   gBuffer.setColor(Color.white);       
                   gBuffer.fillRect(0, 0, width, height);
                   gBuffer.drawImage(splashIm,0,0,this);       
                   drawAnimation();               
                   //Overlay a cute animation       
                   gBuffer.setColor(Color.white);       
                   gBuffer.drawString(Message.toString(), (width/20), (height-8));
         public void drawAnimation() {     
              if (gBuffer == null)       
                   return;     
              if (animationStep < 0)       
                   animationStep = 399;     
              for (int i=0; i<400; i++) {       
                   int thisColor = (int)(((float)(animationStep + i))/(float)400 * (float)256);       
                   while (thisColor > 255) {         
                        thisColor = thisColor-256;       
                   while (thisColor < 0) {         
                        thisColor = thisColor+256;       
                   gBuffer.setColor(new Color(0, 0, thisColor) );
                   gBuffer.drawLine(i, (width/2), i, height);
         public void paint(Graphics g) {     
              if (Buffer != null)       
                   if (g != null)         
                        g.drawImage(Buffer, 0, 0, this);   
         // Use this to change the status message. Note that the redraw   
         // is done elsewhere (FYI, inside the animation thread below)   
         public void setMessage(String message) {     
              Message = new StringBuffer(message);   
         public void start() {
              runner = new Thread(this);     
              runner.start();   
         public void stop() {
              runner.interrupt();     
              runner = null;   
         public void run() {
              try { 
                   while (!Thread.interrupted()) {           
                        buildBuffer();                 
                        //Build the offscreen buffer           
                        this.paint(this.getGraphics());
                        //Draw the offscreen buffer           
                        animationStep-=8;           
                        Thread.sleep(40);        
              catch(InterruptedException e) {}   
         protected void finalize() {     
              stop();     
              this.splashIm.flush();     
              this.splashIm = null;     
              Buffer.flush();     
              Buffer = null;   
    }I use this splashscreen through this class:
    import java.awt.*;
    public class SplashScreen extends javax.swing.JFrame {
         private SplashWindow sw = null;
         public SplashScreen(String titulo, String imagen, int w, int h) {
              super(titulo);
              setSize(w,h);
              Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize();
              Rectangle frameDim = this.getBounds();
              setLocation((screenDim.width-frameDim.width)/2,(screenDim.height-frameDim.height)/2);
              MediaTracker mt = new MediaTracker(this);
              Image splashIm = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource(imagen));
              mt.addImage(splashIm,0);          
              try { 
                   mt.waitForID(0);
              catch(InterruptedException ie) {}
              sw = new SplashWindow(this, w, h, splashIm);
         public void setMensaje(String mensaje) {
              if (sw != null)
                   sw.setMessage(mensaje);
         public void cerrar() {
              sw.dispose();
              this.setVisible(false);
              this.dispose();
    }Maybe some code are in spanish, but you can easily translate to english.
    Regards.

  • A beginner trying to create platform game

    I'm a new programmer and just learning Java from the dummies books... I'm trying to make this Java platform game applet that I guess plays like Megaman/Mario/Castlevania.
    Hmm my question would be that my applet slows down a lot on browsers, and I would like to learn how to double buffer as I've seen people suggest on this forum.
    Also I would like to know why the sound doesn't seem to work on 99% of the people who try it.
    You can check the game here: http://www.info.com.ph/~arivera/game/testmain.html
    And the source code is here: http://www.info.com.ph/~arivera/game/source
    Please give suggestions... my code is still very messy and unoptimized too, please bear with me.
    (Updates may occur on the game itself while I work on it.)

    There's two things you'll want to think about implementing in your applet - active rendering and double buffering as you mentioned.
    Active rendering consists of drawing to the screen in the same thread that runs the game applet. By default, when you call repaint(), the AWT Event thread handles the repainting and gets around to repainting the screen whenever it feels like doing so - sometimes not at all! (well, that's not entirely true, but you get the idea)
    Double buffering entails writing to an offscreen buffer, and then drawing that buffer to the screen.
    Thankfully, both are relatively easy to implement.
    Active rendering is the easier of the two to implement. In your game loop, where you call repaint(), don't! Instead, call paint() directly and use the applets getGraphics() method, which will return a Graphics or Graphics2D object for you to use. So instead of having repaint(), replace it with paint(getGraphics());
    Double buffering is a bit more complicated to implement. I'd suggest trying this after you've tried active rendering. Double buffering includes have an Image field in your applet class. I often call it 'buffer', but there's quite a few other common names you'll come across for it.
    To initialize the image, call the applet's createImage(width, height) method. This will return an Image object. You can get a Graphics object that corresponds to that image by calling its getGraphics() method just like you do with active rendering. You no longer want to have all of the painting being done in the paint() method of your applet. Instead, a new method is in order to handle the painting of the game screen to the buffer. Your paint method then should simply call g.drawImage(...) and draw the backbuffer to the screen.
    A small example:
    public class doubleBufferApplet implements Applet
    Image buffer;
    . . . //Other fields
    public void init()
    buffer = createImage(getWidth(), getHeight()); //returns an Image object the size of the applet and assigns it to buffer
    . . . //Do other initializing
    public void run()
    while(gameIsStillRunning) //Main game loop
    . . . //Run through and update the game
    if(buffer != null)
    drawGame(buffer.getGraphics()) //Draw the game to the backbuffer
    paint(getGraphics()); //Draw the backbuffer to the screen
    public void drawGame(Graphics g)
    . . . //Do your painting here
    public void paint(Graphics g)
    if(buffer != null)
    g.drawImage(buffer, 0, 0, this);
    public void update(Graphics g) //Override the default update() method to avoid Java from calling it randomly
    paint(g);
    I hope that gave you a decent idea of how to go about implementaing active rendering and a buffer. If not, I'll try harder to answer any questions you have (or some of the more experienced users around here will help you out as well I'm sure).

  • The Disappearing Image

    Unfortunatly, I have a large problem I am baffled with. I'm trying to create a Galaxian clone, and am having problem with the animation. I need the little ships to move left & right, and when they reach the screen bounds (0.0, or screenSize.width()), to move down one and move the opposite direction.
    The problem is that after about 5 slow cycles, the images disappear. Completely! I don't know what in the world the problem, but any help at all would be more than appreciated.
    Also, suggestions on how to speed things up would help too.
              public void update(Graphics g) {
                   Graphics2D offgc;
                   Image offscreen = null;
                   Dimension d = getSize();
                   // create the offscreen buffer and associated Graphics
                   offscreen =  createImage(d.width, d.height);
                   offgc = (Graphics2D) offscreen.getGraphics();
                   // clear the exposed area
                   offgc.setColor(getBackground());
                   offgc.fillRect(0, 0, d.width, d.height);
                   offgc.setColor(getForeground());
                   // do normal redraw
                   //Graphics2D g2 = (Graphics2D)g;
                   offgc.drawImage(player.ship, new Double(player.pos.x).intValue(), new Double(player.pos.y).intValue(), null);
                   int i;
                   for (i = 0; i < enemies.length; i++) {
                        if (enemies[i] != null) {
                             offgc.drawImage(enemies.ship, new Double(enemies[i].pos.x - (enemies[i].width/2)).intValue(), new Double(enemies[i].pos.y - (enemies[i].height/2)).intValue(), null);
                   i = 0;
                   //Draw Shots
                   offgc.setColor(Color.black);
                   while ((playerShots[i] != null) && (i < 10)) {
                        Point2D.Double temp = new Point2D.Double(playerShots[i].x, playerShots[i].y - 5);
                        //Point2D.Double temp = new Point2D.Double(playerShots[i].x, 0.0);
                        Line2D shot = new Line2D.Double(playerShots[i], temp);
                        offgc.draw(shot);
                        //g.drawLine(playerShots[i].x, playerShots[i].y - 5, playerShots[i].x, playerShots[i].y + 5);
                        i++;
                   paint(offgc);
                   // transfer offscreen to window
                   g.drawImage(offscreen, 0, 0, null);

    Rather than plough through you code, take a look at this - you can copy and paste it, then plough through mine instead!
    From what I can gather from your code, I think its largely similar - a moving object and a shooter, yes? Any way copy, paste, compile and see. It draws an oval alien rather than uses an image, but it definitely doesn't go out of bounds, its also not completely finished I sort of got it working and as a result got bored once the heavy duty stuff was done - have fun!import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    **   class Alien also builds with Backdrop class
    **   Description: shooting game with 3 levels of difficulty
    **   -author: S. Scott
    **   -version: jdk1.3.1
    **   -date: May 2003
    public class Alien extends JFrame{
       Backdrop drop = new Backdrop();
       int hit, change, ship, i, score=0, x=50, y=50, a=32, b=20;
       boolean win,lose,restart;
       Color []colour = {Color.magenta,Color.yellow,Color.orange,Color.cyan,Color.pink};
    public Alien() {
       setBounds(3,10,500,350);
       setContentPane(drop);
       setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
       setVisible(true);
       javax.swing.Timer t1 = new javax.swing.Timer(40, new ActionListener(){
             public void actionPerformed(ActionEvent e){
                drop.moveAstro();
       t1.start();
    public class Backdrop extends JPanel implements MouseListener{
       Point astro = new Point(60,60);
          public Backdrop(){
             addMouseListener(this);
             addMouseMotionListener(new MouseMotionAdapter() {
             public void mouseMoved(MouseEvent mm) {
                if(mm.getY()>300)ship = mm.getX();
                repaint();
       public void paintComponent(Graphics g){
          super.paintComponent(g);
          Rectangle r = g.getClipBounds();
          Graphics2D g2 = (Graphics2D)g;
          g2.setFont(new Font("", Font.BOLD, 16));
          g2.setColor(Color.black);
          g2.fill(r);
           if((win)||(lose)){
              g2.setColor(Color.white);
              String str="";
                 if(win) str="Game "+(i+1)+" over, "+(4-i)+" to go";
                 if(lose)str="The Alien got away!";
                 if((i==4)&&(win))str="GAME OVER, YOU WIN!";
              g2.drawString(str,155,120);
              if(i!=4)g2.drawString("( click to restart )", 170, 150);
              g2.drawString("score: "+score,380,20);
              if((i!=4)||(lose))restart=true;
           else{      
              g2.setColor(colour);
    g2.fillOval(astro.x,astro.y,a,b);
    g2.setColor(Color.green);
    g2.fillRect(ship-10,318,20,7);
    g2.fillOval(ship-10,314,20,8);
    g2.drawString("||",ship-4,322);
    g2.setColor(Color.black);
    g2.drawString("...",ship-6,319);
    if(change%2==0)g2.drawString("..",astro.x+2,astro.y+5);
    else g2.drawString("..",astro.x+6,astro.y+5);
    g2.setColor(Color.white);
    g2.drawString("__",ship-9,319);
    g2.drawLine(3,290,495,290);
    if(score<0)score=0;
    g2.drawString("score: "+score,380,20);
    public void moveAstro(){
    repaint(astro.x,astro.y,a,b);
    if(change%3==0)astro.x-=3;
    else if(change%4==0)astro.x+=3;
    else if(change%7==0)astro.x+=6;
    else if(change%5==0)astro.x-=5;
    else astro.x+=2;
    if((hit>astro.x)&&(hit<astro.x+a)){
    if((hit>astro.x+a-b)&&(hit<astro.x+a)){
    score +=(i+1)*5;
    astro.y+=20;
    else{
    score +=i+1;
    astro.y+=5;
    if(hit>250)astro.x-=20;
    else astro.x+=20;
    change=(int)(Math.random()*8)+1;
    if((hit<astro.x-a)||(hit>astro.x+(a*2) )){
    astro.y-=10;
    score -=(i+1);
    if((astro.x<5)||(astro.x>480)) {
    astro.x=240;
    astro.y-=20;
    score -=(i+1)*2;
    if(astro.y<10) lose= true;
    if(astro.y>280)win = true;
    if(hit>astro.x) { change=3;hit=astro.x+a+1; }
    else { change=4;hit=astro.x-1;   }
    repaint(astro.x,astro.y,a,b);
    public void shoot(int xs){
    Graphics2D g2 = (Graphics2D)getGraphics();
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setColor(Color.red);
    for(int ys=300-astro.y; ys>10; ys-=3)g2.drawLine(xs,330,xs,ys);
    repaint();
    public void mouseReleased(MouseEvent m){}
    public void mouseEntered (MouseEvent m){}
    public void mouseExited (MouseEvent m){}
    public void mouseClicked (MouseEvent m){}
    public void mousePressed (MouseEvent m){
    if((!win) || (!lose)) {
    if(m.getY()>300){
    shoot(m.getX() );
    hit=m.getX();
    change=m.getX();
    moveAstro();
    if(restart){
    astro.x=80;
    astro.y=80;
    if(win) { score +=(i+1)*6;  i++;  a-=5;  b-=3; }
    if(lose){ score -=(i+1)*6;  i--;  a+=5;  b+=3; }
    if(i<=0){ i=0; a=30; b=18; }
    restart=win=lose=false;
    if(i>4){ i=-1; win=true; }
    public static void main (String[] args) {
    new Alien();

  • Graphics disappearing from canvas

    I am writing an application with a canvas. But the graphics on the canvas are disappearing when the screen is minimised or another window comes on top of the canvas. The code below is a small part of it but the problem occurs in this part of the application. It will draw lines when mouse pressed and dragged on canvsas. The code should run. If anyone could help me I would be really grateful as I can't seem to find the problem and I think it just needs someone who has'nt seen the code before to find the problem.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    public class TestCanvas extends JFrame
       Container c;
       public TestCanvas()
            c = getContentPane();
            TheCanvas can = new TheCanvas();
            JPanel two = new JPanel();
            c.add(can.pad);
            setSize(600,600);
            setVisible(true);
       class TheCanvas extends Canvas implements MouseListener, MouseMotionListener
           Canvas pad;
           public static final int mode_paint = 0;
           public static final int mode_xor = 1;
           public static final int line = 1;
           public static final int drawType = 1;
           public Color drawColor;
           boolean showingPicture = false;
           protected Image offScreen = null;
           public int drawThickness = 1;
           tempLine draftLine;
           boolean dragging = false;
           int oldx = 0;
           int oldy = 0;
          TheCanvas()
             pad = new Canvas();
             pad.setBackground(Color.white);
             pad.setVisible(true);
             pad.setSize(500, 500);
             //setSize(300,300);
             drawColor = Color.black;
             pad.addMouseListener(this);
          pad.addMouseMotionListener(this);
          offScreen = null;
          synchronized public void paint(Graphics g)
         int width = 0;
         int height = 0;
            //offScreen is the image declared at top
         if (offScreen != null)
                  //intislise the widt and heigth depending on if showingpicture is true
              if (!showingPicture)
                       width = offScreen.getWidth(this);
                       height = offScreen.getHeight(this);
              else
                   width = pad.getWidth();
                   height = pad.getHeight();
                    //Draws as much of the specified image as has already
                    //been scaled to fit inside the specified rectangle
                    //The "this" is An asynchronous update interface for receiving
                    //notifications about Image information as the Image is constructed
                    //This is causing problems
              g.drawImage(offScreen, 0, 0, width, height, pad);
              g.dispose();
           synchronized public void drawLine(Color color, int startx, int starty,
                              int endx, int endy, int thickness,
                              int mode)
         int dx, dy;
         Graphics g1 = pad.getGraphics();
         Graphics g2;
         //if image is not intialised to null
         //the getGraphics is used for freehand drawing
         //Image.getGraphics() is often used for double buffering by rendering
            //into an offscreen buffer.
         if (offScreen != null)
             g2 = offScreen.getGraphics();
         else
             g2 = g1;
            //mode is put into the method and XOR is final and equal to 1
         if (mode == mode_xor)
                  //calls the setXOR mode for g1 and g2
                  //Sets the paint mode of this graphics context to alternate
                    //between this graphics context's current color and the
                    //new specified color.
              g1.setXORMode(Color.white);//This will
              g2.setXORMode(Color.white);
         else
                  //Sets this graphics context's current color to the
                    //specified color
              g1.setColor(color);
              g2.setColor(color);
         if (endx > startx)
             dx = (endx - startx);
         else
             dx = (startx - endx);
         if (endy > starty)
             dy = (endy - starty);
         else
             dy = (starty - endy);
         if (dx >= dy)
              starty -= (thickness / 2);
              endy -= (thickness / 2);
         else
              startx -= (thickness / 2);
              endx -= (thickness / 2);
         for (int count = 0; count < thickness; count ++)
              g1.drawLine(startx, starty, endx, endy);
              g2.drawLine(startx, starty, endx, endy);
              if (dx >= dy)
                  { starty++; endy++; }
              else
                  { startx++; endx++; }
            //Disposes of this graphics context and releases any system
            //resources that it is using.
         g1.dispose();
         g2.dispose();
          //nothing happens when the mouse is clicked
        public void mouseClicked(MouseEvent e)
        //When the mouse cursor enters the canvas make it the two
        //straigth lines type
        public void mouseEntered(MouseEvent e)
         pad.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
        //When mouse exits canvas set to default type
        public void mouseExited(MouseEvent e)
         pad.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        public void mousePressed(MouseEvent e)
             // Save the coordinates of the mouse being pressed
         oldx = e.getX();
         oldy = e.getY();
         // If we are doing lines, rectangles, or ovals, we will show
         // draft lines to suggest the final shape of the object
         //Draw type is a publc int which can be changed
            draftLine = new tempLine(drawColor, oldx, oldy, oldx,
                                 oldy, drawThickness);
            // Set the draw mode to XOR and draw it.
            drawLine(draftLine.color, draftLine.startx,
            draftLine.starty, draftLine.endx,
            draftLine.endy, drawThickness, this.mode_xor);
        //mouse listener for when the mouse button is released
        public void mouseReleased(MouseEvent e)
              // Erase the draft line
              drawLine(draftLine.color, draftLine.startx, draftLine.starty,
                    draftLine.endx, draftLine.endy, drawThickness,
                    this.mode_xor);
              // Add the real line to the canvas
              //When the imput changes to "mode_paint" it is drawen
              //on the canvas
              drawLine(drawColor, oldx, oldy, e.getX(), e.getY(),
                    drawThickness, this.mode_paint);
              dragging = false;
        public void mouseDragged(MouseEvent e)
            // Erase the old draft line
            drawLine(draftLine.color, draftLine.startx, draftLine.starty,
              draftLine.endx, draftLine.endy, drawThickness,
              this.mode_xor);
            // Draw the new draft line
            draftLine.endx = e.getX();
            draftLine.endy = e.getY();
            drawLine(draftLine.color, draftLine.startx, draftLine.starty,
              draftLine.endx, draftLine.endy, drawThickness,
              this.mode_xor);
         public void mouseMoved(MouseEvent e)
         //declare  a class for the line shown before the is as wanted
        class tempLine
         public Color color;
         public int startx;
         public int starty;
         public int endx;
         public int endy;
         public int thickness;
         public tempLine(Color mycolor, int mystartx, int mystarty,
                      int myendx, int myendy, int mythickness)
             color = mycolor;
             startx = mystartx;
             starty = mystarty;
             endx = myendx;
             endy = myendy;
             thickness = mythickness;
    public static void main(String[] args)
         TestCanvas one = new TestCanvas();
    }

    Thanks for replying, I really appreciate it. I have made the changes but the problem is still occurring. I'll show you the code below. If you have any suggestions I would really appreciate it.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    public class TestCanvas extends JFrame
       Container c;
       public TestCanvas()
            c = getContentPane();
            TheCanvas can = new TheCanvas();
            JPanel two = new JPanel();
            c.add(can);
            setSize(600,600);
            setVisible(true);
       class TheCanvas extends Canvas implements MouseListener, MouseMotionListener
           Canvas pad;
           public static final int mode_paint = 0;
           public static final int mode_xor = 1;
           public static final int line = 1;
           public static final int drawType = 1;
           public Color drawColor;
           boolean showingPicture = false;
           protected Image offScreen = null;
           public int drawThickness = 1;
           tempLine draftLine;
           boolean dragging = false;
           int oldx = 0;
           int oldy = 0;
          TheCanvas()
             //pad = new Canvas();
             //pad.
                setBackground(Color.white);
             //pad.
                setVisible(true);
             //pad.
                setSize(500, 500);
             //setSize(300,300);
             drawColor = Color.black;
                addMouseListener(this);
          addMouseMotionListener(this);
          offScreen = null;
          synchronized public void paint(Graphics g)
         int width = 0;
         int height = 0;
            //offScreen is the image declared at top
         if (offScreen != null)
                  //intislise the widt and heigth depending on if showingpicture is true
              if (!showingPicture)
                       width = offScreen.getWidth(this);
                       height = offScreen.getHeight(this);
              else
                       width = getSize().width;
                            height = getSize().height;
                   //width = pad.getWidth();
                   //height = pad.getHeight();
                    //Draws as much of the specified image as has already
                    //been scaled to fit inside the specified rectangle
                    //The "this" is An asynchronous update interface for receiving
                    //notifications about Image information as the Image is constructed
                    //This is causing problems
              g.drawImage(offScreen, 0, 0, width, height, this);
              g.dispose();
           synchronized public void drawLine(Color color, int startx, int starty,
                              int endx, int endy, int thickness,
                              int mode)
         int dx, dy;
         Graphics g1 = getGraphics();
         Graphics g2;
         //if image is not intialised to null
         //the getGraphics is used for freehand drawing
         //Image.getGraphics() is often used for double buffering by rendering
            //into an offscreen buffer.
         if (offScreen != null)
             g2 = offScreen.getGraphics();
         else
             g2 = g1;
            //mode is put into the method and XOR is final and equal to 1
         if (mode == mode_xor)
                  //calls the setXOR mode for g1 and g2
                  //Sets the paint mode of this graphics context to alternate
                    //between this graphics context's current color and the
                    //new specified color.
              g1.setXORMode(Color.white);//This will
              g2.setXORMode(Color.white);
         else
                  //Sets this graphics context's current color to the
                    //specified color
              g1.setColor(color);
              g2.setColor(color);
         if (endx > startx)
             dx = (endx - startx);
         else
             dx = (startx - endx);
         if (endy > starty)
             dy = (endy - starty);
         else
             dy = (starty - endy);
         if (dx >= dy)
              starty -= (thickness / 2);
              endy -= (thickness / 2);
         else
              startx -= (thickness / 2);
              endx -= (thickness / 2);
         for (int count = 0; count < thickness; count ++)
              g1.drawLine(startx, starty, endx, endy);
              g2.drawLine(startx, starty, endx, endy);
              if (dx >= dy)
                  { starty++; endy++; }
              else
                  { startx++; endx++; }
            //Disposes of this graphics context and releases any system
            //resources that it is using.
         g1.dispose();
         g2.dispose();
          //nothing happens when the mouse is clicked
        public void mouseClicked(MouseEvent e)
        //When the mouse cursor enters the canvas make it the two
        //straigth lines type
        public void mouseEntered(MouseEvent e)
         this.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
        //When mouse exits canvas set to default type
        public void mouseExited(MouseEvent e)
         this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        public void mousePressed(MouseEvent e)
             // Save the coordinates of the mouse being pressed
         oldx = e.getX();
         oldy = e.getY();
         // If we are doing lines, rectangles, or ovals, we will show
         // draft lines to suggest the final shape of the object
         //Draw type is a publc int which can be changed
            draftLine = new tempLine(drawColor, oldx, oldy, oldx,
                                 oldy, drawThickness);
            // Set the draw mode to XOR and draw it.
            drawLine(draftLine.color, draftLine.startx,
            draftLine.starty, draftLine.endx,
            draftLine.endy, drawThickness, this.mode_xor);
        //mouse listener for when the mouse button is released
        public void mouseReleased(MouseEvent e)
              // Erase the draft line
              drawLine(draftLine.color, draftLine.startx, draftLine.starty,
                    draftLine.endx, draftLine.endy, drawThickness,
                    this.mode_xor);
              // Add the real line to the canvas
              //When the imput changes to "mode_paint" it is drawen
              //on the canvas
              drawLine(drawColor, oldx, oldy, e.getX(), e.getY(),
                    drawThickness, this.mode_paint);
              dragging = false;
        public void mouseDragged(MouseEvent e)
            // Erase the old draft line
            drawLine(draftLine.color, draftLine.startx, draftLine.starty,
              draftLine.endx, draftLine.endy, drawThickness,
              this.mode_xor);
            // Draw the new draft line
            draftLine.endx = e.getX();
            draftLine.endy = e.getY();
            drawLine(draftLine.color, draftLine.startx, draftLine.starty,
              draftLine.endx, draftLine.endy, drawThickness,
              this.mode_xor);
         public void mouseMoved(MouseEvent e)
         //declare  a class for the line shown before the is as wanted
        class tempLine
         public Color color;
         public int startx;
         public int starty;
         public int endx;
         public int endy;
         public int thickness;
         public tempLine(Color mycolor, int mystartx, int mystarty,
                      int myendx, int myendy, int mythickness)
             color = mycolor;
             startx = mystartx;
             starty = mystarty;
             endx = myendx;
             endy = myendy;
             thickness = mythickness;
    public static void main(String[] args)
         TestCanvas one = new TestCanvas();
    }

  • What's the best way to create a "texture-snapshot" of a 3D plane?

    Hello, my intention is to use a top view, set in parallel projection, with axis x=0,y=100,z=0 for picking up a snapshot of a 3D plane positioned at origin, obviously "y" depends by dimensions of the plane (I have also problems to understand why I must use View.setScreenScale to obtain a depth effect).
    The problem comes when I want to grab an hi-res screenshot image, because the texture size is always limited by the monitor size.
    I tried using some offscreen buffer, but it seems that it must be of the same size of the source onscreen canvas... so in brief how can I create a topographic texture?

    This is PhotoMerge result
    This is WLPG
    This is a manual merge
    Before anyone comments on the poor image quality, I know. Its not my photography.
    The beach huts were in an arc which doesn't help.
    You can see that the photomerged image has not 'understood' the image and has bad destortion on the doors of some huts. The blend lines are also visible

Maybe you are looking for