Displaying a BufferedImage

Hello,
I'm building a program that needs to display a BufferedImage. I created a sub class of JPanel whom's only purpose is to display a BufferedImage, so instead of using drawImage, could I simply assign the Graphics2D object of my BufferedImage to the one of my component (see code below)?
paintComponent(Graphics g){
    BufferedImage pic = getPic();
    g = pic.getGraphics();
}

Hello,
I'm building a program that needs to display a
BufferedImage. I created a sub class of JPanel whom's
only purpose is to display a BufferedImage, so
instead of using drawImage, could I simply assign the
Graphics2D object of my BufferedImage to the one of
my component (see code below)?
paintComponent(Graphics g){
BufferedImage pic = getPic();
g = pic.getGraphics();
Hi,
No that doesn't work. You can't change what g originally references. You only got a copy of that reference in the method.
What is your actual question?
/Kaj

Similar Messages

  • Displaying a BufferedImage in a GUI

    I want to display a BufferedImage in my GUI.
    The BufferedImage is a screen snapshot created by the createScreenCapture() method in the Robot class. I know how to save it to file, but how would i display it in a GUI without saving it ??
    Would be really grateful for any help.
    Thanks
    Rob

    In the painting method of your GUI, you could cast the Graphics object into a Graphics2D. The Graphics2D has a method
    drawImage(BufferedImage img, BufferedImageOp op, int x, int y);

  • Displaying a BufferedImage in a JSP

    I want to build a JPG image as a BufferedImage using
    JPEGImageDecoder.decodeAsBufferedImage() and then set this
    BufferedImage object as an attribute of a user's Session (this is all done within a servlet). I then want a JSP to be able to display the image as part of the page, via the session object. I'm doing this because I want to create the images on the server but not write them to disk so that they will expire along with the user's Session and I don't have to do any clean up of the image files. Is there a way to do this ? I have tried something like the below with no success:
    in the servlet:
    HttpSession session = request.getSession(true);
    session.setAttribute("testImage", regionOfInterestImage);
    in the JSP:
    <img src="<%= session.getAttribute("testImage") %>"
    alt="IMAGE NOT FOUND">
    If anyone has an idea as to how I can pull this off then please
    respond ! I can't find much at all on this sort of thing in all the
    references I have available.
    Thanks in advance...
    -James

    I don't know how exactly to do this, but typically you would produce the image in a servlet, setting the mime type appropriately and then have a normal image link <img src="/servlet/url/servletname"> in your jsp page, to display it.

  • Problem displaying TIFF BufferedImage. It's all black.

    Hello,
    I am new to Java2D and I have a problem. I have a BufferedImage, bi1, created from a RenderedOp object (containing a grayscale TIFF image). I now would like to copy a part of bi1 to another BufferedImage, bi2. Creating and displaying bi1 works fine, but when I try to display bi2 it's all black. Since that is the default background color of BufferedImage, I guess this meens that my copying wasn't successful.
    So my question is: How do I set the data in bi2 correctly?
    Thanks in advance.
    My code looks something like this:
    FileSeekableStream stream = null;
    try {
    stream = new FileSeekableStream(args[0]);
    } catch (IOException e) {
    e.printStackTrace();
    System.exit(0);
    ParameterBlock params = new ParameterBlock();
    params.add(stream);
    TIFFDecodeParam decodeParam = new TIFFDecodeParam();
    decodeParam.setDecodePaletteAsShorts(true);
    RenderedOp image = JAI.create("tiff", params);
    int tiff_width = image.getWidth();
    int tiff_height = image.getHeight();
    BufferedImage bi1 = image.getAsBufferedImage();
    BufferedImage bi2 = new BufferedImage(tiff_width, (int)Math.round(tiff_height*0.35), BufferedImage.TYPE_BYTE_GRAY);
         bi2.getRaster().setRect(bi1.getData(new Rectangle(0,(int)Math.round(tiff_height*0.65),tiff_width,(int)Math.round(tiff_height*0.35))));
    ScrollingImagePanel panel = new ScrollingImagePanel(bi2, tiff_width, tiff_height);
    Frame window = new Frame("");
    window.add(panel);
    window.pack();
    window.show();

    The BufferedImage class has method
    public BufferedImage getSubimage(int x, int y, int w, int h);
    Probably you might use it
    bi2=bi1.getSubImage(0,0, newWidth,newHeight);
    hope this helps
    Stas

  • Simple question about displaying a BufferedImage in Swing

    I have a program that is working on medium-sized BufferedImages (600x600 or so). I really just need to display them. Right now, I'm doing:
    panel.add(new JLabel(new ImageIcon(bufferedImage)));
    It works, of course, but is this the right way to do it? Or is there some better way to express that?
    Thanks

    I guess I associate "icons" with actions, or links to things, or some kind of UI component, rather than just a way to display an image. But it's fine, I'll use it.
    Thanks

  • Display a BufferedImage to screen

    Hi,
    There maybe an answer somewhere already, but I didn't see it.
    As I understand it, rendering can happen on different outputs. They
    can be screen, printer, or offscreen buffer. Each of these three has
    their own way of creating a Graphics object. If I have a BufferedImage
    (which seems a better way of storing an image if image manipulation
    is required a lot), how do I display it onto screen? Thanks.
    Xiang

    blah blah paint(Graphics g) {
        g.drawImage(bufferedImage, 0, 0, this);

  • Displaying and manipulating an BufferedImage

    I have to program a game in Java for a university course. Therefore I need to display a quite big image (the game field).
    I tried to display the image with an own Panel Class ImagePanel:
    public class ImagePanel extends JPanel {
        private BufferedImage background;
        /** Creates a new instance of ImagePanel */
        public ImagePanel(BufferedImage image) {
            this.setBackground(image);
        public void paintComponent(Graphics graphic) {
            super.paintComponent(graphic);
            graphic.drawImage(getBackground(), 0,0,getBackground().getWidth(),getBackground().getHeight(), this);
        public Dimension getPrefferedSize() {
            return new Dimension(getBackground().getWidth(),getBackground().getHeight());
        public BufferedImage getBackground() {
            return background;
        public void setBackground(BufferedImage background) {
            this.background = background;
    }I display a BufferedImage using the ImagePanel on a JScrollPane. The image is displayed, but the scrollbars doesn't appear (the Horizontal and VerticalScrollBarPolicy is set to AS_NEEDED) :
            BufferedImage map = ImageIO(UrlToFile);
            Graphics2D graphic = map.createGraphics();
            graphic.drawRenderedImage(map, null);
            imagePanel = new ImagePanel(map);
            jScrollPane1.add(imagePanel);
            jScrollPane1.getViewport().setView(imagePanel);   I also want to resize the image from time to time and put another image on the image. Can anyone tell me how to display the image, scroll and resize it? I also have to put other (small) images on the map, is graphic.DrawRenderedImage(buffImage,null) the best way to do this?

    First read How to Use Scroll Panes:
    http://java.sun.com/docs/books/tutorial/uiswing/components/scrollpane.html
    You don't add your ImagePanel to the scroll pane, you set the client using the scroll pane constructor or setViewportView.
    Also you need to set the preferred size of the scroll pane to be smaller than the preferred size of your ImagePanel if you want to see the scroll bars.
    If you want to resize your image you can set a new preferred size for your ImagePanel, and then call ImagePanel.revalidate.
    You just need to change the ImagePanel a bit so it will scale the image to its preferred size.
    public class ImagePanel extends JPanel {
        private BufferedImage background;
        /** Creates a new instance of ImagePanel */
        public ImagePanel(BufferedImage image) {
            this.setBackground(image);
            setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
        public void paintComponent(Graphics graphic) {
            super.paintComponent(graphic);
            graphic.drawImage(getBackground(), 0,0,getPreferredSize().getWidth(),getPreferredSize().getHeight(), this);
        public BufferedImage getBackground() {
            return background;
        public void setBackground(BufferedImage background) {
            this.background = background;
    }If you want to draw on top of your image you can use one of the drawImage functions in [url http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Graphics2D.html]Graphics2D.

  • Fastest way to load a BufferedImage on a JPanel

    I am looking for the fastest way to display a BufferedImage on a JPanel.
    I am using JAI to take in photo files (JPG, BMP, GIF, TIFF, PNG) and create thumbnails (BufferedImage).
    I was reading through the forums and saw you can either
    1)overwrite the Graphics method or
    2)imageicon->JLabel->JPanel
    Currently, I am doing number 2, but I was wondering what the best way truly is.

    as you arn't doing any animation or that kind of thing, using Swing Components will work just fine.

  • Display Image from buffer Image

    Hi,
    I have bufferdImage I want to display the bufferedImage in my jsp page. Displaing the images is a part of the page. Is it possible to pass the bufferedImage data to servlet and using the servlet Can I display the image by just calling the Servlet from jsp.

    Get2win4world wrote:
    Hi,
    I have bufferdImage I want to display the bufferedImage in my jsp page. Displaing the images is a part of the page. Is it possible to pass the bufferedImage data to servlet and using the servlet Can I display the image by just calling the Servlet from jsp.Apparently, that is the appropriate process of doing it.
    You need to think of encoding respective image format and you can stream the output through a servlet and use *<img/>* tags to call the servlet URL accordingly.
    Please findout the below example where we are using JPEGImage encoding and making an attempt to stream the image.
    package com.krim.utility.servlet;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import com.sun.image.codec.jpeg.JPEGImageEncoder;
    import com.sun.image.codec.jpeg.JPEGCodec;
    import java.awt.image.BufferedImage;
    public class SimpleImageServlet extends HttpServlet {
            protected void processAction(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
                    BufferedOutputStream out = null;           
                    BufferedImage myImage = null;               
                    ByteArrayOutputStream bos = null;
                    byte imageBuffer[] = null;
                    JPEGImageEncoder jpg = null;
                   try{
                     myImage = (BufferedImage)request.getAttribute("bufferedImage"); 
                     bos = new ByteArrayOutputStream();
                     jpg = JPEGCodec.createJPEGEncoder(bos);
                     jpg.encode(image);
                     imageBuffer = bos.toByteArray();
                     out = new BufferedOutputStream(response.getOutputStream(),imageBuffer.length);
                     response.setContentType("image/jpeg");
                     response.setContentLength(bos.size());
                     out.write(imageBuffer);
                     out.flush();
               }catch(Exception exp){
                    throw ServletExeption(exp.getMessage());
               } finally{
                    if(out != null)
                     try(out.close();)catch(Exception e){}
                   if(bos != null)
                     try(bos.close();)catch(Exception e){}
                   jpg = null;
                   imageBuffer = null;
            protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
                 processAction(request,response);
            protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
                 processAction(request,response);
    }Usage in jsp can be like the below where we have a action that could be called with a unique ID which can fetch appropraite BufferedImage.
    <img src="<%=request.getContextPath()%>/image?id=XXXXYYYZZZ"/>In the same way you can think of implementing similar thing for formats like PNG,GIF & etc...According to your requirement and need of the situation.
    Hope that helps :)
    REGARDS,
    RaHuL

  • Displaying a BufferdImage in an Applet

    Hi all,
    I am trying to display a BufferedImage, stored on a host computer, in an applet that will be viewed over the internet. The applet works fine when I run it in an appletviewer, but when I put it in an html file the image doesn't show up. Is there some other way to pre-load the image into the applet or something? I can do everything else fine once I have the image file buffered into the applet, using ImageIO. The image will not have to change or anything unusual, I just want it available to the applet. It will be stored in the same directory as the applet.
    Thanks in advance.

    Ottobonn wrote:
    OK, here is the full description of my situation:
    I have an applet, that will be stored on a server. In the same directory as the applet, I will also have a jpeg image, that the applet will end up using. However, I am having trouble getting the image into my program. I have tried ImageIO's read() method, and I have also tried getImage(URL location, String imgName)
    I haven't been able to get the image with either of these successfully, and I am wondering if there is a quick way to simply create a BufferedImage object out of the image file in the local directory.
    The applet runs fine in an appletviewer, or when instantiated and put in an application's frame. However, when the applet is put in an html file, it can't access the image it needs anymore. Here is an example of what I have tried, using ImageIO:
    BufferedImage puzzleImage;
    File imageFile = new File("image.jpg");
    ImageIO imageGetter = new ImageIO();
    Uh...That's not a URL, that's a File object. The File object looks on the user's own machine.
    Also, you don't need to instantiate ImageIO. The methods you'll use are static.
    try{
    puzzleImage = imageGetter.read(imageFile);
    }catch(Exception e){}And don't catch exceptions silently.
    I think you want something more like this:
    BufferedImage puzzleImage;
    try {
       puzzleImage = ImageIO.read(this.getClass().getResource("image.jpg"));
    } catch(Exception e) {
        e.printStackTrace();
    }

  • Trying to Load a BufferedImage from a PNG through JNI

    Yes I realize that I can load it directly through Java and not go through JNI, but I need this to test correctly as my C code will aquire images without saving to Disk and I want Java code to manipulate the images without saving to disk. The image Im trying to load is a 800x600 PNG image.
    So I have the code
    import java.io.ByteArrayInputStream;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import com.sun.media.jai.widget.DisplayJAI;
    class ImageLoader{
         static{
              System.loadLibrary("LoadImage");
         private static native byte[] loadImage();
         public static void main(String[] args){
    byte[] f = loadImage();
              InputStream s= new ByteArrayInputStream(f);
              BufferedImage bi;
              try {
                   bi = ImageIO.read(s);
                   displayBufferedImage(bi, "test");
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
          * Utility method for display a BufferedImage.<br>
          * @param  image input image
          * @param  title window title string
         public static void displayBufferedImage(BufferedImage image, String title)
              JFrame frame = new JFrame();
             frame.setTitle(title);
             //frame.getContentPane().add(new DisplayTwoSynchronizedImages(sourceImgBI, resultImgGray));
             frame.getContentPane().add(new JScrollPane(new DisplayJAI(image)));
             //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             //frame.pack();
             frame.setSize(300,300);
             frame.setLocationRelativeTo( null );
             frame.setVisible(true); // show the frame.
         }and I have the JNI c code as
    char* result;
    JNIEXPORT jbyteArray JNICALL Java_ImageLoader_loadImage
      (JNIEnv * env, jclass jclassj){
                   int fd = open("test.png",  O_RDWR, S_IRUSR|S_IWUSR );
                   int size = (800*600*4);
                   result = (char*)malloc(size);
                   read(fd, result, size);
                   jbyteArray return_result;
                   return_result = env->NewByteArray(800*600);
                   env->SetByteArrayRegion(return_result, 0, 800*600, (jbyte*)result);
                   //free(result);
                   return return_result;
         }but when I try to run the code I get the following error
    javax.imageio.IIOException: Error reading PNG image data
         at com.sun.imageio.plugins.png.PNGImageReader.readImage(PNGImageReader.java:1287)
         at com.sun.imageio.plugins.png.PNGImageReader.read(PNGImageReader.java:1552)
         at javax.imageio.ImageIO.read(ImageIO.java:1438)
         at javax.imageio.ImageIO.read(ImageIO.java:1342)
         at ImageLoader.main(ImageLoader.java:31)
    Caused by: java.io.EOFException: Unexpected end of ZLIB input stream
         at java.util.zip.InflaterInputStream.fill(InflaterInputStream.java:240)
         at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158)
         at java.io.BufferedInputStream.fill(BufferedInputStream.java:235)
         at java.io.BufferedInputStream.read1(BufferedInputStream.java:275)
         at java.io.BufferedInputStream.read(BufferedInputStream.java:334)
         at java.io.DataInputStream.readFully(DataInputStream.java:195)
         at com.sun.imageio.plugins.png.PNGImageReader.decodePass(PNGImageReader.java:1084)
         at com.sun.imageio.plugins.png.PNGImageReader.decodeImage(PNGImageReader.java:1188)
         at com.sun.imageio.plugins.png.PNGImageReader.readImage(PNGImageReader.java:1280)
         ... 4 moreI think that Im on the right track because Java is recognizing that this is a PNG image, but Im not sure whats wrong. I don't know much about the formats, so I know nothing about PNG's, maybe someone else can help me here.
    Note: I ran the code
                   BufferedImage bi2 = ImageIO.read(new File("test.png"));
                   displayBufferedImage(bi2, "test2");and the image loads fine, so there is no issue with the image itself.

                   int fd = open("test.png", O_RDWR, S_IRUSR|S_IWUSR );Why are you opening the image file read/write? Why not read-only?
                   int size = (800*600*4);Here you're assuming the image is 800*600. Are you sure that's the case? Also you should write sizeof int here instead of 4.
                   result = (char*)malloc(size);Here you aren't checking for the possibility that result is null.
                   read(fd, result, size);Here you are ignoring the result returned by read(), so you are ignoring the possibilty that it was 0 or less than 'size'. Either are possible.
                   jbyteArray return_result;
                   return_result = env->NewByteArray(800*600);Here again you aren't testing for return_result == null.
                   env->SetByteArrayRegion(return_result, 0, 800*600, (jbyte*)result);Here you should be checking for Java exceptions. Also you shouldn't be repeating the 800*600 here, make it a constant or a variable somewhere.
                   //free(result);You need that free, otherwise you have a memory leak. If the image really is a constant 800*600 in size I would allocate 'result' on the stack so you don't need to housekeep it.
    Also you are never closing the input file!
    Caused by: java.io.EOFException: Unexpected end of ZLIB input streamSo clearly you didn't read all the image. That could be due to guessing wrong about 800*600 or getting a short read when reading the file.
    I think that Im on the right track because Java is recognizing that this is a PNG imageI agree. It starts like a PNG image, so you read something, but it doesn't end like one, so you didn't read it all.> and the image loads fine, so there is no issue with the image itself.
    Good test. Note that your Java code makes no assumption about the size of the image.

  • Confusion with Image/BufferedImage

    Hello,
    I'm trying to write an applet that displays and modifies local image files (gif). I'm running into some confusion with the different image APIs and drawing methods though.
    I want to read the files, display them, and then create new images from sections of the original ones. I wrote an applet that succesfully loads and displays files as Image objects, but then I saw that BufferedImage has a method getSubImage() that I thought I could use to create the new images.
    But my problem is that even without manipulating the images, I can't get them to display as BufferedImages. Here's the code, where I try to display the series of images twice, once as Image, once as BufferedImage, but the BI come out as black squares.
    public class myapplet extends Applet
         BufferedImage[] img = new BufferedImage[NUM_PICS];
         Image[] im = new Image[NUM_PICS];
         public void init()
              Toolkit t = Toolkit.getDefaultToolkit();
              Graphics2D bg;
              MediaTracker tracker = new MediaTracker (this);
              for(int i = 0;i<NUM_PICS;i++)
                   try
                        im[i] = t.getImage(gen.getLogo());
    //the getLogo method is from a class I wrote -
    //it returns a string with a filename
                   catch(Exception e)
                        System.out.println("ERROR: "+e.getMessage());
                   img[i] = new BufferedImage(70, 70,BufferedImage.TYPE_INT_RGB);
    bg = img[i].createGraphics();
    bg.drawImage(im[i],0,0,this);
         public void paint(Graphics g)
              Graphics2D g2 = (Graphics2D)g;
              for(int i=0;i<NUM_PICS;i++)
                   g.drawImage(im[i],10,i*70,this);
                   g2.drawImage(img[i],null,80,i*70);
    Any help would be great.

    You have to use the MediaTracker before drawing the image onto the BufferedImage:
    try {
    im[i] = t.getImage(gen.getLogo());
    tracker.addImage(im[i], i);
    tracker.waitForID(i);

  • BufferedImage performance

    Hi All,
    I have a thread that serves me a java.awt.Image. Many of these Images come through per second. Each time an Image comes through I create a new BufferedImage and call the paintComponent method on my JPanel to display the BufferedImage. The problem is that it is really slow. Does anyone have some performance tips for me that would make the generation of the BufferedImage quicker?
    Example Code:
    public void displayImage(Image image){
    BufferedImage buff = new BufferedImage(image.getWidth(this), image.getHeight(this), BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = buff.createGraphics();
    g2d.drawImage(image,0,0,this);
    paintPanel(buff);
    The method paintPanel(BufferedImage) overrides paintComponent and draws the image to the JPanel.
    Any help would be greatly appreciated.

    If you already have an Image, why do you need to make it a BufferedImage?

  • Jsp and JPanel problem

    Hello. I've been to this forum many times, but have always been a bit gunshy about posting anything of my own. Now I have a problem I haven't seen before, so here goes. I have a JPanel in a java program that has all sorts of other componants added to it. I am trying to display the whole thing in a jsp page. This is what I am doing in the java file to return the image ("display" is the JPanel):
    public byte[] getImage(){
        int w = display.getWidth();
        int h = display.getHeight();
        BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        display.paint(img.createGraphics());
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(img, "jpeg", os);
        return os.toByteArray();
    }and then in the jsp page I say:
    <%@ page contentType="image/jpeg" %>
    <%@ page import="myPackage.MyClass" %>
    <%
         MyClass picture = new MyClass();
         byte[] b = picture.getImage();
         OutputStream os;
         os = response.getOutputStream();
         os.write(b);
         os.flush();
    %>And the problem is that the page is displaying a blank JPanel and none of the componants that were added to it. If I save the the JPanel as a jpeg in the java program, though, it does contain all the componants, so I am not sure what I am doing wrong here. If there is some way to get the all the JPanel componants returned, that would be great to know. Thanks for any help.

    nope, that didn't work.
    Maybe I am going about solving the problem all wrong. The JPanel and its componants are kind of like a template. When a user of the system submits their information it automatically puts the data into the template and displays it on screen as a jpg. It works when I save the jpg as a file from the java program but not when i send the byte array to the jsp server. It just shows the blank panel....
    Is there a better way to go about doing this?

  • Drawing a special cursor: completely repaint everytime or only a region?

    Hello, I'm currently building an application which displays a BufferedImage. When I move the cursor in the the component that displays the BufferedImage my app draws a special cursor. It's a square which is moved only if my current position is dividable by 16 (if there was a grid, it would change it's position when the mouse moves to another square in the grid, it is around the square that the mouse occupies). At first, I was only using on thread so the application was a little laggy and my cursor thing didn't work too well. So I decided to use another thread to take care of my cursor. The drawing is in another class (external to the drawing class), therefore, I use getGraphics (since my drawing class subclasses JComponent). I signal a draw by changing a variable. I have to erase my old cursor to draw the new one. The problem is that my component "'flashes" gray instead of staying the way it should be (which is black, for now). Here are my questions: Why does it flash gray ? and what should I do to change that?
    Here's my code:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    class Cursor implements Runnable {
         public boolean draw;
         public int[] iCursorCoord;
         public JComponent drawSurface;
         private Thread t;
         private Rectangle cursor;
         Cursor(){
              cursor = new Rectangle(0,0,15,15);
              t = new Thread(this);
              iCursorCoord = new int[2];
              iCursorCoord[0] = 0;
              iCursorCoord[1] = 0;
              draw = false;
              drawSurface = null;
         Cursor(int[] initCoord){
              cursor = new Rectangle(initCoord[0],initCoord[1],15,15);
              t = new Thread(this);
              iCursorCoord = new int[2];
              iCursorCoord[0] = 0;
              iCursorCoord[1] = 0;
              draw = false;
              drawSurface = null;
         Cursor(Rectangle rect){
              cursor = rect;
              t = new Thread(this);
              iCursorCoord = new int[2];
              iCursorCoord[0] = rect.x;
              iCursorCoord[1] = rect.y;
              draw = false;
              drawSurface = null;
         Cursor(JComponent drawSurf){
              cursor = new Rectangle(0,0,15,15);
              t = new Thread(this);
              iCursorCoord = new int[2];
              iCursorCoord[0] = 0;
              iCursorCoord[1] = 0;
              draw = false;
              drawSurface = drawSurf;
         Cursor(JComponent drawSurf, Rectangle rect){
              cursor = rect;
              t = new Thread(this);
              iCursorCoord = new int[2];
              iCursorCoord[0] = rect.x;
              iCursorCoord[1] = rect.y;
              draw = false;
              drawSurface = drawSurf;
         Cursor(JComponent drawSurf, int[] initCoord){
              cursor = new Rectangle(initCoord[0], initCoord[1], 15, 15);
              t = new Thread(this);
              iCursorCoord = new int[2];
              iCursorCoord[0] = initCoord[0];
              iCursorCoord[1] = initCoord[1];
              draw = false;
              drawSurface = drawSurf;
         public void init(){
              t.start();
         public void run(){
              while(true){
                   if(!draw) continue;
                   draw = false;
                   cursor.x = iCursorCoord[0];
                   cursor.y = iCursorCoord[1];
                   System.out.println("Inside Cursor::run()");
                   Graphics2D gfx = (Graphics2D) drawSurface.getGraphics();
                   this.completePaint(gfx);
                   Color current = gfx.getColor();
                   gfx.setColor(new Color(84,255,3));
                   gfx.draw(cursor);
                   gfx.setColor(current);
         private void completePaint(Graphics2D gfx){
              int layer = MapMaker.getLayerMode();
              if(layer != 4){
                   BufferedImage bi = MapMaker.getCurrentMap().getData(MapMaker.getLayerMode());
                   gfx.setPaint(new TexturePaint(bi, new Rectangle(0,0,MapMaker.getCurrentMap().getWidth()*16, MapMaker.getCurrentMap().getHeight()*16)));
                   gfx.fillRect(0, 0, MapMaker.getCurrentMap().getWidth()*16, MapMaker.getCurrentMap().getHeight()*16);
                   //gfx.drawImage(bi, null, 0,0);     
              } else {//Will be implemented later, render will be modified
                   System.out.println("Will be implemented later");
    }P.S.: This is only part of my code. There are other classes that I do not post because I believe it is not necessary. I will post the full code if needed.

    You need to override the paint(Graphics g) method. E.g.:
    public class MyPanel extends JPanel {
         public void paint(Graphics g) {
                   super.paint(g);
                    // ... do draw code here
    }The reason your app is flashing is because your code only executes
    when the thread is requests it to. Inbetween the time your code is
    executing, other threads are calling the paint(Graphics g) method.
    Gray is the default color used in painting.
    You can use a thread to call the repaint() method, but no drawing
    should be done in the thread.

Maybe you are looking for

  • Unique Id for each device

    Hi, Im building a positioning system on Android through Flash. I want each android device to send the server the gps position and an unique id. Im having some trouble finding any functions or classes that gives me unique id of the device. The unique

  • Dynamic SQL and GRANT CREATE ANY TABLE

    hi gurus, i have a dynamic SQL in a procedure where a table will be created from an existing table without data. strSQL:='create table ' || strTemp || ' as select * from ' || strArc || ' where 1=2'; execute immediate strSQL; without GRANT CREATE ANY

  • Can I download ebooks from Amazon to My Ipad?

    I used my netbook to download kindle ebooks directly to my Kindle Device and would like to know if I can download those that are say that are available for Amazon or Apple? I know I can download to my PC and transfer to my Appile Ipad but I thinkk th

  • Everytime i push play on itunes it quits 'unexpectedly'?

    ever since i "upgraded" to lion, my itunes quit playing anything.  I have downloaded new versions twice, i have searched on the apple site for help (absolutely worthless) and I have tried writing apple (no response) so can any one help or do i trash

  • Default text for html:textarea..

    Hi All. How to populate a textarea in struts(<html:textarea>) with some default text. Waiting for your suggestion in this regard.