Issues Drawing Image

Okay, so I've made a JPanel based class, but whenever I try to draw an image, it just comes up blank. Now, I know it can read the image because if I place the wrong path or name, it gives an error, but I think perhaps I'm doing something else wrong... Actually, I'm sure of it. Here's my code I've come up with:
package planets;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JPanel;
public class image extends JPanel {
     private static final long serialVersionUID = 1L;
     private Image img;;
     public image() {
          this.img = Toolkit.getDefaultToolkit().getImage("earth.gif");
     public void changeImage(Image img) {
          this.img = img;
          repaint();
     @Override
     public void paintComponent(Graphics g) {
          g.drawImage(img, super.getWidth()/2-150, super.getHeight()/2-150, this);
     }What could I possibly have wrong?
Edit: I thought I might go ahead and put the code tags in for everybody's general sanity.

First of all learn Java naming standards. "image" is not a standard class name.
What could I possibly have wrong?Well, we don't know for sure because you don't show us how the panel is actually used in your program.
In the future, and for more help create a [url http://sscce.org]SSCCE, that demonstrates the incorrect behaviour.
As a guess, many layout managers use the preferred size of a component. You didn't specify a preferred size (or override the getPreferredSize() method) and the default size is 0 so Swing thinks there is nothing to paint. Add the following:
setPreferredSize( new Dimension(?, ?) );

Similar Messages

  • Problems drawing images form another class

    Ok as the title says I'm having trouble drawing images from a different class. I have a class that represents a plane and it has a draw' method that draws its .gif image.
    public void draw (Graphics g)
    g.drawImage(planepic , xPos, yPos, null)
    then in my main class in the paint method i have
    plane.draw(g);
    I think my problem is the null for my image observer. I tried using null as my image observer and i got a error saying i can't make a static reference to a non static method.
    I've done some research because i never really understood static but i still don't quite get it.
    Also when I use this as my image observer i get a error in my plane object.
    I also just tried passing and making a object for my main class and i still got the static error.
    Any help is appreciated and thanks in advance

    Ok as the title says I'm having trouble drawing
    images from a different class. I have a class that
    represents a plane and it has a draw' method that
    draws its .gif image.
    public void draw (Graphics g)
    g.drawImage(planepic , xPos, yPos, null)
    in my main class in the paint method i have
    plane.draw(g);
    I think my problem is the null for my image observer.
    I tried using null as my image observer and i got a
    error saying i can't make a static reference to a non
    static method. Use a minimal implementation of the ImageObserver to be sure.
    public class Plane implements ImageObserver
    public boolean imageUpdate(
    Image img,int infoFlags,int x,int y,int width,int height)
       switch(infoFlags)
          case ALLBITS:
                    return false;
          case SOMEBITS:
                    return true;
          default:
                return true;
    I've done some research because i never really
    understood static but i still don't quite get it.
    Also when I use this as my image observer i get a
    error in my plane object.
    I also just tried passing and making a object for my
    main class and i still got the static error.
    Any help is appreciated and thanks in advanceWhen you call draw(g) from your other class you hand it a Graphics context that you instantiated somewhere else ie: in another class. Without a more complete example it is really impossible to determine your issue for sure,
    but if I was to guess I would say you need to make sure that the Graphics context handed to the draw(Graphics) method was instantiated from a Component that was already visible. ie: Do a f
    Frame.createImage() from your parent frame after iyou have already called setVisible(true); In other words I suspect you are making and Image from some other Component that is not yet visible. That however is a guess so if not the issue post the rest of the code or at least a minimal implementation that demonstrates this.
    About static:
    static means the class/variable is the same throughout ALL classes of that type and if changed in one instance it will change and thus be the same for all instances.
    You CAN call static by referencing the base class Object without having to instantiate.
    ie:given
    public class SomeClass
    static String name;
    static String getName
       if(name == null)
          name = "DefaultName";
       return name;
    }Thus you could call..
      String name = SomeClass.getName();As opposed to
    SomeClass myClass = new SomeClass();
          myClass.getName();This can get you in trouble if you try to make a method that is static
    that then tries to reference non static variables.
    ie:
    public class SomeClass
    int x;
    static String name;
    SomeClass()
       x=0;
    static String getName
       if(name == null)
          name = "DefaultName";
       x++;
       return name;
    }In this case SomeClass.getName(); will throw and exception because it is trying to access[b] x  from a static context .
    Hope that clears that up for you; if not post a more complete example.
    Good Luck!
    (T)

  • Draw image using paint() only once.

    I am having performance issues with my application. It is creates a graph like data display. The display is static. However each time paint is called the image is re-rendered. I want it only rendered once to improve performance, I tried to do this using the following code:
    public void paint(Graphics g){
              if (alreadyRun) return;
              //super.paint(g);
              alreadyRun = true;
    // draw graphics code
    }Unfortunately the required image appears for a moment then disappears. Is there any way to render the image only once? Also, are there any other performance improving measures I can take? I was thinking of rendering only the part of the image that appears on screen (my graphics display is usually bigger than the actual screen size)

    The common way to deal with performance like this is to draw the graph (or whatever) onto a BufferedImage then have the paint (or paintComponent in Swing) simply draw the image. The single draw image is quite fast and keeps the pixel values persistant across paints. If you already have a single image as the thread title hints, the paint shouldn't create much of a performance hit. The reason you are seeing your image disappear is that any time a window is resized, repacked, moved, covered up, or a multitude of other reasons, it calls paint again, so even with static data, there will be times the paint method is called again, causing your drawing to disappear.

  • Need help diagnosing cause of printing issue w/ image distortion

    Hello, I'm looking for some expert advice for my print issue with image distortion (see above) on my files once setup and proofed by my printer.
    I have a large PSD background file out of photoshop (CMYK, 170mb psd) that is being placed into an InDesign document. No preflight errors, all correct SWOP cmyk settings, and I keep having issues where images distort on my printers proofs - they seem unable to explain the issue and can't offer any other suggestions beyond ("just try resaving/uploading again" which of course has an added fee with each upload...).
    The files are all fine on our end: on-screen, on our cmyk proofs, and our saved PDFs/packaged files. But everytime our printer opens these they seem to have these distorted image problems - scrambled images (almost as if there was a ghosted transparent image in the distorted area), strange lines (see above, and color distortion (usually greens and pinks, see above).
    Is this an issue with my settings/file formats? Maybe the issue lies on our printers end? I'll keep checking this throughout the day and provide quick answers to anyone who can help me get to the bottom of this.
    Adobe forums have been a huge help in years past so I decided this was by best bet for a resolution from those who know more than myself (or my printer), thanks for taking the time to help!
    - Ian

    Hello, I'm looking for some expert advice for my print issue with image distortion (see above) on my files once setup and proofed by my printer.
    I have a large PSD background file out of photoshop (CMYK, 170mb psd) that is being placed into an InDesign document. No preflight errors, all correct SWOP cmyk settings, and I keep having issues where images distort on my printers proofs - they seem unable to explain the issue and can't offer any other suggestions beyond ("just try resaving/uploading again" which of course has an added fee with each upload...).
    The files are all fine on our end: on-screen, on our cmyk proofs, and our saved PDFs/packaged files. But everytime our printer opens these they seem to have these distorted image problems - scrambled images (almost as if there was a ghosted transparent image in the distorted area), strange lines (see above, and color distortion (usually greens and pinks, see above).
    Is this an issue with my settings/file formats? Maybe the issue lies on our printers end? I'll keep checking this throughout the day and provide quick answers to anyone who can help me get to the bottom of this.
    Adobe forums have been a huge help in years past so I decided this was by best bet for a resolution from those who know more than myself (or my printer), thanks for taking the time to help!
    - Ian

  • How can I draw image in a vbean?

    How can I draw image in a vbean?
    this is my code :
    import java.awt.BorderLayout;
    import java.awt.Image;
    import java.awt.Graphics;
    import java.net.MalformedURLException;
    import java.net.URL;
    import com.sun.jimi.core.Jimi;
    import oracle.forms.handler.IHandler;
    import oracle.forms.properties.ID;
    import oracle.forms.ui.VBean;
    public class PrintEmailLogo extends VBean {
         URL url;
         Image img;
         boolean ImageLoaded = false;
         public void paint(Graphics g) {
              if (ImageLoaded) {
                   System.out.println("yes~~~");
                   g.drawImage(img, 0, 0, null);
              } else
                   System.out.println("no~~~");
         public boolean imageUpdate(Image img, int infoflags, int x, int y, int w,
                   int h) {
              if (infoflags == ALLBITS) {
                   System.out.println("yes");
                   ImageLoaded = true;
                   repaint();
                   return false;
              } else
                   return true;
         public void init(IHandler arg0) {
              super.init(arg0);
              try {
                   url = new URL("file:print/77G.gif");
                   img = Jimi.getImage(url);
                   Image offScreenImage = createImage(size().width, size().height);
                   Graphics offScreenGC = offScreenImage.getGraphics();
                   System.out.println(offScreenGC.drawImage(img, 0, 0, this));
              } catch (MalformedURLException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
    but when I run it in forms
    when it run Graphics offScreenGC = offScreenImage.getGraphics();
    It throw a exception:
    java.lang.NullPointerException     at com.avicit.aepcs.calendar.PrintEmailLogo.init(PrintEmailLogo.java:72)     at oracle.forms.handler.UICommon.instantiate(Unknown Source)     at oracle.forms.handler.UICommon.onCreate(Unknown Source)     at oracle.forms.handler.JavaContainer.onCreate(Unknown Source)     at oracle.forms.engine.Runform.onCreateHandler(Unknown Source)     at oracle.forms.engine.Runform.processMessage(Unknown Source)     at oracle.forms.engine.Runform.processSet(Unknown Source)     at oracle.forms.engine.Runform.onMessageReal(Unknown Source)     at oracle.forms.engine.Runform.onMessage(Unknown Source)     at oracle.forms.engine.Runform.processEventEnd(Unknown Source)     at oracle.ewt.lwAWT.LWComponent.redispatchEvent(Unknown Source)     at oracle.ewt.lwAWT.LWComponent.processEvent(Unknown Source)     at java.awt.Component.dispatchEventImpl(Unknown Source)     at java.awt.Container.dispatchEventImpl(Unknown Source)     at java.awt.Component.dispatchEvent(Unknown Source)     at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)     at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)     at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)     at java.awt.Container.dispatchEventImpl(Unknown Source)     at java.awt.Component.dispatchEvent(Unknown Source)     at java.awt.EventQueue.dispatchEvent(Unknown Source)     at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)     at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)     at java.awt.EventDispatchThread.pumpEvents(Unknown Source)     at java.awt.EventDispatchThread.run(Unknown Source)
    I change it to:
    import java.awt.BorderLayout;
    import java.awt.Image;
    import java.awt.Graphics;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.swing.JFrame;
    import com.sun.jimi.core.Jimi;
    import oracle.forms.handler.IHandler;
    import oracle.forms.properties.ID;
    import oracle.forms.ui.VBean;
    public class PrintEmailLogo extends VBean {
         URL url;
         Image img;
         public void paint(Graphics g) {
              try {
                   url = new URL("file:print/77G.gif");
                   img = Jimi.getImage(url);
                   g.drawImage(img, 0, 0, this));
              } catch (MalformedURLException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
         public void init(IHandler arg0) {
              super.init(arg0);
    But it display nothing.
    It isn't paint continuous.
    what's wrong in my vbean?
    please help me.

    The following code works fine for me:
    package oracle.forms.fd;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import oracle.forms.handler.IHandler;
    import oracle.forms.properties.ID;
    import oracle.forms.ui.CustomEvent;
    import oracle.forms.ui.VBean;
    public class test extends VBean {
      private URL url;
      private URL m_codeBase; 
      private Image img;
    public void paint(Graphics g) {
      // draw the image
      g.drawImage(img, 0, 0, this);
    public void init(IHandler arg0) {
       super.init(arg0);
       // load image file
       img = loadImage("file:///c:/coyote.jpg");   
    public test()
        super();
       *  Load an image from JAR file, Client machine or Internet URL  *
      private Image loadImage(String imageName)
        URL imageURL = null;
        boolean loadSuccess = false;
        Image img = null ;
        //JAR
        imageURL = getClass().getResource(imageName);
        if (imageURL != null)
          try
            img = Toolkit.getDefaultToolkit().getImage(imageURL);
            loadSuccess = true;
            return img ;
          catch (Exception ilex)
            System.out.println("Error loading image from JAR: " + ilex.toString());
        else
          System.out.println("Unable to find " + imageName + " in JAR");
        //DOCBASE
        if (loadSuccess == false)
          System.out.println("Searching docbase for " + imageName);
          try
            if (imageName.toLowerCase().startsWith("http://")||imageName.toLowerCase().startsWith("https://"))
              imageURL = new URL(imageName);
            else if(imageName.toLowerCase().startsWith("file:"))
              imageURL = new URL(imageName);
            else
              imageURL = new URL(m_codeBase.getProtocol() + "://" + m_codeBase.getHost() + ":" + m_codeBase.getPort() + imageName);
            System.out.println("Constructed URL: " + imageURL.toString());
            try
              img = createImage((java.awt.image.ImageProducer) imageURL.getContent());
              loadSuccess = true;
              System.out.println("Image found: " + imageURL.toString());
              return img ;
            catch (Exception ilex)
              System.out.println("Error reading image - " + ilex.toString());
          catch (java.net.MalformedURLException urlex)
            System.out.println("Error creating URL - " + urlex.toString());
        //CODEBASE
        if (loadSuccess == false)
          System.out.println("Searching codebase for " + imageName);
          try
            imageURL = new URL(m_codeBase, imageName);
            System.out.println("Constructed URL: " + imageURL.toString());
            try
              img = createImage((java.awt.image.ImageProducer) imageURL.getContent());
              loadSuccess = true;
              System.out.println("Image found: " + imageURL.toString());
              return img ;
            catch (Exception ilex)
                    System.out.println("Error reading image - " + ilex.toString());
          catch (java.net.MalformedURLException urlex)
            System.out.println("Error creating URL - " + urlex.toString());
        if (loadSuccess == false)
          System.out.println("Error image " + imageName + " could not be located");
        return img ;
    }Francois

  • Can one add more than one photo layer to a draw image?

    I cannot seem to find a way to add more than one photo or photo layer to a Draw image, but the Draw page on Adobe seems to imply multiple photos can be added. How might I accomplish this? Thanks for your time.

    Unfortunately, Draw is currently limited to one photo layer, and only one photo within that layer.
    Hope that helps,
    Frank
    Draw Engineering

  • Looking for an app where i can draw images then text them?

    Looking for an app where I can draw images then text them?

    Just write Draw into the MAS searchbox in the upper right corner and you will be presented with a plethora of drawing/sketching apps of varying abilities and pricing.

  • Specification to Draw image on a page

    Can any one tell me exact Specification to draw image on a page.

    What don't you understand from the PDF Reference?
    You need an Image XObject and the Do operator in the content stream.
    Leonard

  • Accesibility Issues with Image element

    Hi All,
    I've image element inside a table column. Image used is '~Icon/RedLed'.
    Image source and tool tip are bound properly.
    But we are facing an accessibility issue in this.
    When accessibility mode is set to X, image tool tip reads as
    'Image - Unavailable - Error Exist - Row 6 column Status'
    where 'Error Exist' is the tooltip we are providing.
    The problem is with 'Unavailable' word which is also coming up.
    Also, Image is also rendered, so there is no issue like image path is not found therefore Unavailable word is comin.
    Does anyone have any clue why this could be comnig up.
    Regards
    Manas

    Hi Manas,
    Check this blog to place image in your table.But the blog is to show image in ALV table, apply same logic.
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/1190424a-0801-0010-84b5-ef03fd2d33d9

  • Issues with Images when used w/ Caption Widget & Book File Size Q

    Hi Everyone,
    I was having issues with images not showing up and determined it was the caption widget causing the issue. I now have one of two issues happening consistently. Either the image does not show at all or just the caption box with bkgd gray and caption text shows, but without the image.
    Anyone else have this issue?
    Ay ideas would be greatly appreciated. I wasw just about finished with this project when this started!
    Also, the size of the book is considerably larger than I realized.It is 81 mb. . . How does this compare to any of your books?
    THANKS SO MUCH!
    Belinda

    Belinda,
    I can't speak to your main issue, as I cannot recreate the problem over here.
    As a guess, have you checked to make sure you're not running out of harddrive space? iBA can consume space quickly, and behaves oddly when it begins to run out of room.
    But as far as filesize goes, I can only wish for an 81 MB book. Mine is currently a little over 2 GB and growing. Tonight I had to split it into 2 volumes just so iBooks Author can run at a reasonable pace. I was getting tired of waiting 1-2 minutes after dragging a video around on the page before I could get control of the program again.
    You should note that Apple is expecting large filesizes for this new Multi-Touch format. The docs on iTunesConnect say the largest allowed upload size for a book is 16GB 2BG (see link below)
    Message was edited by: mudmas

  • How draw image into frame in applet

    How draw image into frame in applet.Please give my simple example code.

    http://search.java.sun.com/search/java/index.jsp?qt=%2Bdraw+%2Bimage+%2Bpanel+%2Bhow&nh=10&qp=&rf=1&since=&country=&language=&charset=&variant=&col=javaforums

  • Blast from the past: How do I draw image maps in Dreamweaver CC 2014?

    Need to update some old stuff, and can´t find where to draw image-maps on images.

    First, you need to be in Design View to get the image map tools to appear.
    Once there, the image map icons should show when you select an image. If they don't, you may have your Properties panel collapsed. In the bottom right corner of the Properties panel, there's a tiny triangle, click that to expand the panel to include the image map tools.

  • Drawing images in JComponent

    Hi,
    I have an application laid out as Figure 1 depicts.
    JFrame
    |
    | JMenuBar
    |-----------------------------------------
    | ------------------JPanel - appPanel
    | |--------------------------------|
    | | ---|------------------ JPanel - displayPanel
    | | | |
    | |----------------|---------------|
    | |-------------------------- JComponent - jcanvas
    |
    | |--------------------------------|
    | | ----|----------------------- JPanel - controlPanel
    | | |
    | |--------------------------------|
    |
    |--------------------------------------------
    Figure 1
    The problem I am having is that:
    theJPanel (appPanel) contains two JPanels (displayPanel and controlPanel) and I am adding a JComponent called JCanvas
    to the displayPanel and I use it to draw images on it of type BufferedImage. Now, the image is displayed without any problem
    but when I resize the application (JFrame) I lose my image. I know the JCanvas (JComponent) is being redrawn because I can
    temporarily see the image but something is overwriting the image. I have set appPanel, displayPanel, controlPanel to opaque
    but I still loose the image.
    Of point maybe, if I access the JMenuBar the image will appear less what part of the menu bar obscures it.
    The appPanel, controlPanel, and displayPanel are created in the IDE. Where as, the JCanvas is a seperate class extending JCompoment
    and it has it own paintComponent method to do the image rendering and is added to the displayPanel when instantiated.
    What I don't understand is why isn't the image staying visible after a frame resize?
    Thanks,
    Bob

    Hopefully this will fit.
    You will have to provide your own image file.
    * SwingPaintDemo2.java
    * Created on Sep 27, 2008, 10:57:22 AM
    * Company: 
    * Copyright: Sep 27, 2008
    * Version:
    import javax.swing.SwingUtilities;
    import javax.swing.JFrame;
    import javax.swing.BorderFactory;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.imageio.ImageIO;
    import javax.swing.JComponent;
    * @author
    public class SwingPaintDemo2 {
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
        private static void createAndShowGUI() {
            System.out.println("Created GUI on EDT? " +
                SwingUtilities.isEventDispatchThread());
            JFrame f = new JFrame("Swing Paint Demo");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(new MyPanel());
            f.pack();
            f.setVisible(true);
    class MyPanel extends JComponent {
        BufferedImage bi;
        File file;
        Dimension d = new Dimension();
        boolean fullScreen = false;
        public MyPanel() {
            setBorder(BorderFactory.createLineBorder(Color.black));
            file = new File("g://java/images/dido_img.jpg");
            try {
                bi = ImageIO.read(file);
            } catch (IOException ex) {
                Logger.getLogger(MyPanel.class.getName()).
                    log(Level.SEVERE, null, ex);
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(350, 350);
        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) this.getGraphics();
            d = this.getPreferredSize();
            if (d.width == 0 || d.height == 0) {/* error */
            if (!fullScreen) {
                int px = (d.width - bi.getWidth()) / 2;
                int py = (d.height - bi.getHeight()) / 2;
                g2.drawImage(bi, null, px, py);
            } else {
                g2.drawImage(bi, 0, 0, d.width, d.height,
                    0, 0, bi.getWidth(), bi.getHeight(), null);
    }

  • Graphics refuses to draw Images

    I was attempting to make an applet today, but for some reason, I can't draw Images. I had a little program going, but I decided to make this basic test applet to see if Images would draw at all.
    import java.awt.*;
    import java.applet.*;
    public class TestApplet extends Applet
         Image im;
         public void init()
              setSize(300, 400);
              im = getImage(getDocumentBase(), "Picture.GIF");
         public void start()
              repaint();
         public void paint(Graphics g)
              g.drawImage(im, 10, 10, this);
              g.drawString("I can draw a string", 10, 10);
         public void stop()
         public void destroy()
    }The string gets drawn fine, but the image just refuses to show up. Any idea why?
    Message was edited by:
    Guest42

    //  <applet code="TestApplet" width="300" height="400"></applet>
    import java.awt.*;
    import java.applet.*;
    public class TestApplet extends Applet
         Image im;
        public void init()
            setSize(300, 400);
            im = getImage(getDocumentBase(), "Picture.GIF");
            loadImage();
        private void loadImage()
            MediaTracker tracker = new MediaTracker(this);
            tracker.addImage(im, 0);
            try
                tracker.waitForID(0);
            catch(InterruptedException ie)
                System.err.println("interrupt: " + ie.getMessage());
            int status = tracker.statusID(0, false);
            String results = "";
            if((status & MediaTracker.COMPLETE) == MediaTracker.COMPLETE)
                results += "COMPLETE";
            if((status & MediaTracker.ABORTED) == MediaTracker.ABORTED)
                results += "ABORTED";
            if((status & MediaTracker.ERRORED) == MediaTracker.ERRORED)
                results += "ERRORED";
            System.out.println("results = " + results);
        public void start()
    //        repaint();
        public void paint(Graphics g)
            g.drawImage(im, 10, 10, this);
            g.drawString("I can draw a string", 10, 10);
        public void stop()
        public void destroy()
    }

  • How to draw image in different dpi?

    I wonder is there any approach can be used to draw a image in different dpi, such as 144dpi, in a JPanel?
    'cause my image processed from other tools is not good, if I can draw image in a high dpi, then the image will looks much better, though the image becomes smaller.
    Note: no SCALE!

    I have a image which is 152dpi, then, how does the Widows draws this image? It looks much better than scale the 72dpi image to the same size.
    Really puzzled-_-                                                                                                                                                                                                                                                                                                                               

Maybe you are looking for