Image getWidth & getHeight

I got this problem in getting the size of the image display on the screen. I try to used getWidth & getHeight and print it out but the value is 0. I try many time will different combination but still can't.
This is the example:
map = getToolkit().getImage("Map3.jpg");
MediaTracker track=new MediaTracker(this);
track.addImage(map,0);
try{track.waitForID(0);}
catch(InterruptedException ie){}
int w=this.getWidth(map);
int h=this.getHeight(map);
Actually, I am trying to resize the image to which fit the JPanel I created but fail. Any idea?

I presume you mean to be using map.getWidth(this) and map.getHeight(this)?
It's sufficient to use map.getWidth(null) and map.getHeight(null) in this context.
However, are you sure that the image is being loaded?
Put the image in the root directory of your project and try using "/Map3.jpg" instead.
Hope this helps.

Similar Messages

  • Image getwidth() getheight() problem

    When i run the code below first time it returns like;
    width=-1
    height=-1
    but when i refresh the page and runing code for secad time width and height returns correct;
    why this happen, i couldnt solve....need help,any advice?thank you
    Image resmim = Toolkit.getDefaultToolkit().getImage(klasor_adres+resim_adi);
    int width=resmim.getWidth(null);
    int height=resmim.getHeight(null);

    i have found the problem...the problem caused by this;
    we must control for the image to be fully loaded to servlet and do this by adding a media tracker...
    Image resmim = Toolkit.getDefaultToolkit().getImage(klasor_adres+resim_adi);
              MediaTracker mediaTracker = new MediaTracker(new Container());
              mediaTracker.addImage(resmim, 0);
              mediaTracker.waitForID(0);then we make get width and height operations

  • Image.getWidth(null) and image..getHeight(null)  returns -1

    Hi ,
    Plz tell me whats wrong with code
    import java.awt.Image;
    import java.awt.Toolkit;
    public class ImgSize {
        public static void main(String args[]) {
            Image image = Toolkit.getDefaultToolkit().getImage("Picture.jpg");
            double width = image.getWidth(null);
            double height = image.getHeight(null);
            System.out.println("width :" + width + "-- height :" + height);
            getImageDimesion("Picture.jpg");
        public static void getImageDimesion(String abc) {
            Image image = Toolkit.getDefaultToolkit().getImage(abc);
            double width = image.getWidth(null);
            double height = image.getHeight(null);
            System.out.println("width :" + width + "-- height :" + height);
    }output:
    width :-1.0-- height :-1.0
    width :2592.0-- height :1944.0
    There is no difference in main function getWidth/ getHeight and function getImageDimension getWidth/ getHeight
    If u remove getWidth and getHeigth in the main function i.e comment the 1st four lines in main function then the output is
    Output
    width :-1.0-- height :-1.0
    Plz help in understanding this.
    Thanks
    Venkat

    Toolkit images are not loaded until they are first drawn or you request a property from it (such as getWidth). To force the image to load and wait for it to finish loading, you can use the MediaTracker class. The ImageIcon class has one built in.
    Image image = Toolkit.getDefaultToolkit().getImage("Picture.jpg");
    new ImageIcon(image); //loads the image

  • Java.awt.Image getWidth() and getHeight() not working!

    Right- this is want I want to do.
    I have a background image which is added as a background image to a third party API class which extends Java.awt.Container. Such container is then added to the Content Pane of MyClass (which extends JFrame)
    I want to read the width and height of the image and resize MyClass accordingly.
    Problem is calling theImage.getWidth(MyClass.this) or theImage.getWidth(theThirdPartyAPIContainer) always return -1 and -1 denoting that no information is available.
    What do I need to do to obtain the height and width?

    Post here, cos don't know your email.
    Anyway
    - Can't use setPreferredSize because the Conatiner which is added to the ContentPane is a Awt Component not a Swing JComponent!
    - Also, the background is added AFTER the this.pack()and this.show().
    -I figured out that I could access Insets.top, Insets.left, Insets.right, Insets.bottom.
    I have basically the following
    |JMenuBar |
    L____________________________________________|
    | |
    | |
    | |
    | Third Party Class extending java.awt.Container |
    | containing an image of known size |
    | |
    L____________________________________________|
    I am fine for the width I do
    Insets frameInsets = this.getInsets();
    width = image.getWidth() + frameInsets.left + frameInsets.right;
    Height is the problem
    After some Trial an error it LOOKS on Solaris as if the following is right-
    height = image.getHeight()+frameInsets.top+ myJMenuBar.getSize()+getHeight+ myJMenuBar.getInsets().top + myJMenuBar.getInsets().bottom
    I cannot comprehend whether this is just a coincidence or not as I don't know why frameInsets.bottom should in any case be excluded.
    Here are the dimensions-
    frameInsets.left = 6
    frameInsets.right= 6
    frameInsets.top =28
    frameInsets.bottom = 6
    JMenuBar height = 23
    JMenuBar's Insets.top = 1
    JMenuBar's Insets.bottom = 1
    What should be the 'correct' calculations and does the Insets for the JMenuBar and the JFrame overlaps?

  • Problems with Image.getWidth()

    I need to have the dimensions (width and height) of an image available, though the image will never be displayed. I have tried using the image.getWidth(this) function outside of the JPanel's paint() method, but to no avail. Actually, only within the paint method was I able to retrieve the information that I needed. So, my question is: how can I gain this information about an image without it being drawn to the screen?
    I had heard that an image, though retrieved and registered into a MediaTracker, is not really "loaded" until it is used or displayed. Is this true?

    Yes, I have been experimenting with the ImageObserver.ImageUpdate() method, but I am a bit unfamiliar with it. Do you know of a decent reference? I am new to Java and the introductory books I have only glean over the topic. I assume I am to be concerned with the ALLBITS flag parameter of the imageObserver method?

  • Image.getWidth(ImageObserver obs) returns -1

    hello everyone i have used following code to load an image
    URL location=Sprite.class.getClassLoader().getResource(path);
        img=Toolkit.getDefaultToolkit().getImage(location);and this code to draw an image:
    g2d.drawImage(img, x, y, this);now i need to know the width and height of image for detecting collision.
    getWidth() and getHeight() returns -1.
    System.out.println(img.getWidth(this));my images are getting displayed in the frame.but when i try to access width and height of an image then it returns -1 which means width and height of image is not known yet.
    help !!
    thanks.

    sorry.
    This problem is in my game code.Since the code is very long so i am giving a small code reflecting my problem
    import java.awt.Image;
    import java.awt.Toolkit;
    import java.net.URL;
    import javax.swing.*;
    import java.awt.Graphics;
    public class Sprite extends JPanel
    private JFrame frame;
    private Image img;
    public Sprite()
    frame=new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500,400);
    frame.getContentPane().add(this);
    frame.setVisible(true);
    URL location=Sprite.class.getClassLoader().getResource("small.jpg");
    img=Toolkit.getDefaultToolkit().getImage(location);
    this.repaint();
    System.out.println(img.getWidth(null));
    public void paintComponent(Graphics g)
    g.drawImage(img,150,150,this);
    public static void main(String[] args)
    new Sprite();
    }So i want the width and height of an image.But when i try to get it, it just returns -1 which means width and height is not known yet, according to java doc.
    if i use img=new ImageIcon("small.jpg").getImage() to load an image and if i access the width and height of an image using img.getWidth(ImageObserver obs) then i get correct value of width and height.
    i want to use above code that i provided to load an image.So pls help me out.Why it is returning -1 ?.
    Edited by: JGarage on Dec 6, 2008 7:59 AM
    Edited by: JGarage on Dec 6, 2008 8:00 AM

  • Images loading from url

    Hi All !
    I am trying to load images onto a canvas using url source.
    The images loaded are forming a map , so its important that
    every image will be
    exactly in the wright place.
    The problem is that sometimes an image is not loaded , and I
    get error 504 "Gateway RequestTimeout" ,
    what i want to do is shorten the time of the error so if an
    image isnt loaded after 5 seconds i will get the error
    and reload it. How do i change the timeout of the loading ?
    or maybe i should use another method to load the images to
    the canvas ?
    10x alot !
    mr. flex ;)

    hi,
    looks like PaintComponent() instead of paint did the job.
    thanks a million..
    for those interested in loading images, I find ImageIcon very limited and at the end I found a better solution :
    public class ImageComponent extends JComponent implements ImageObserver{
        private Image image;
        public void loadImage(URL imageURL){           
                image = Toolkit.getDefaultToolkit().getImage(imageURL);
                prepareImage(image,getWidth(),getHeight(), this);
        public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height){
            System.out.print("."); // loading progress...
        public void paintComponent(Graphics g){
            if(image!=null){
                 g.drawImage(image,0,0,null);
    }it is far nicer as it displays dots while loading... up to you to attach progress bars or favorit loading guizmo...
    DrLeinster.

  • Problem loading & displaying images from URL

    hi,
    I can't manage to display an image into a component from a url... here is what my code looks like :
    public class ImageComponent extends JComponent{
        private ImageIcon imageIcon;
        public void paint(Graphics g){
            if(imageIcon!=null){
                imageIcon.paintIcon(this, g, posX, posY);
        private void loadsImage(String imageURL){
            imageIcon = new javax.swing.ImageIcon(imageURL);
            invalidate();
    }when I call loadImage with a proper url, the image doesn't seem to be loaded...
    it might be that the image is big and long to come (also my connection isn't that fast)... but forcing the repaint of the component (by hiding/showin the component's window) after a good while doesn't do much...
    can anybody tell me where I'm doing wrong...
    cheers,
    DrLeinster

    hi,
    looks like PaintComponent() instead of paint did the job.
    thanks a million..
    for those interested in loading images, I find ImageIcon very limited and at the end I found a better solution :
    public class ImageComponent extends JComponent implements ImageObserver{
        private Image image;
        public void loadImage(URL imageURL){           
                image = Toolkit.getDefaultToolkit().getImage(imageURL);
                prepareImage(image,getWidth(),getHeight(), this);
        public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height){
            System.out.print("."); // loading progress...
        public void paintComponent(Graphics g){
            if(image!=null){
                 g.drawImage(image,0,0,null);
    }it is far nicer as it displays dots while loading... up to you to attach progress bars or favorit loading guizmo...
    DrLeinster.

  • Drop support only works on the second drop

    Hi,
    I created an ImageComponent that accepts drops and displays images. The problem I'm facing is that the drop is only accepted on the second try. For some reason the getDataFlavors() method on the TransferSupport returns an empty array on the first drop.
    I'm dropping a JPG file from the desktop on my ImageComponent. I'm running it in debug mode with the latest version of Eclipse on Mac OS X 10.6.
    I hope someone can help me solve this problem.
    Thanks in advance,
    Stef
    Here is my source code:
    public class ImageComponent extends JComponent {
         private static final long serialVersionUID = 1L;
         private BufferedImage image;
         private final Vector<ImageChangeListener> listeners = new Vector<ImageChangeListener>();
         public ImageComponent() {
              setTransferHandler(new ImageTransferHandler());
         public synchronized void addImageChangeListener(ImageChangeListener listener) {
              listeners.add(listener);
         public synchronized void removeImageChangeListener(ImageChangeListener listener) {
              listeners.remove(listener);
         public void setImage(BufferedImage image) {
              this.image = image;
              paint(getGraphics());
         @Override
         public Dimension getPreferredSize() {
              if (image != null) {
                   BufferedImage scaledImage = Utils.scaleImage(image, getWidth(), getHeight());
                   return new Dimension(scaledImage.getWidth(), scaledImage.getHeight());
              } else {
                   return super.getPreferredSize();
         @Override
         public void paint(Graphics g) {
              if (g != null) {
                   g.clearRect(0, 0, getWidth(), getHeight());
                   super.paint(g);
                   if (image != null) {
                        BufferedImage scaledImage = Utils.scaleImage(image, getWidth(), getHeight());
                        int x = ((getWidth() - scaledImage.getWidth()) / 2);
                        int y = ((getHeight() - scaledImage.getHeight()) / 2);
                        g.drawImage(scaledImage, x, y, null);
         private void fireImageChange() {
              ImageChangeEvent event = new ImageChangeEvent(this, image);
              for (ImageChangeListener listener : listeners) {
                   listener.imageChanged(event);
              setImage(image);
         private class ImageTransferHandler extends TransferHandler {
              @Override
              public boolean canImport(TransferSupport support) {
                   for (DataFlavor dataFlavor : support.getDataFlavors()) { // Returns an empty array on the first drop
                        System.out.println(dataFlavor);
                   return support.isDataFlavorSupported(DataFlavor.javaFileListFlavor); // returns false on the first drop, true on consecutive drops
              @Override
              public boolean importData(TransferSupport support) {
                   if (canImport(support)) {
                        BufferedImage newImage = readFirstImage(support);
                        if (newImage != null) {
                             setImage(newImage);
                             fireImageChange();
                             return true;
                        } else {
                             return false;
                   } else {
                        return false;
              private BufferedImage readFirstImage(TransferSupport support) {
                   try {
                        List<File> fileList = (List<File>) support.getTransferable().getTransferData(
                                  DataFlavor.javaFileListFlavor);
                        if (fileList != null && fileList.size() > 0) {
                             File file = fileList.get(0);
                             return ImageIO.read(file);
                        } else {
                             return null;
                   catch (IIOException exception) {
                        return null;
                   catch (IOException exception) {
                        exception.printStackTrace();
                        return null;
                   catch (UnsupportedFlavorException exception) {
                        return null;
                   catch (Exception e) {
                        return null;
    }

    I'm on a relatively new system, where I haven't set much up, but I don't get any package-name completion which highlights the point that this is shell (and shell config) dependent.  What shell are you using?  Have you done anything to configure completion?  Do you have any pacman related aliases (or functions)?
    I do, by default bash settings it seems, get filename completion with pacman -R, so the options are files in the current directory.
    EDIT: (duh) just installing bash-completion now - new results momentarily - but more on point, this further highlghts the shell + config dependent nature of this.  EDIT2: works as expected with bash-completion installed.
    Last edited by Trilby (2013-07-15 21:58:12)

  • How fast is Image.getHeight ()?

    Can anyone tell me how fast the Image class' getHeight () and getWidth () methods are? Do these do some sort of complicated analysis on the picture, or do they simply return a variable that Java computes when the image is created?
    Here's the thing: I'm making a game. In this game, there are a lot of collisions. I check every object for collision with every other object. Thus I have about n^2 collision checks if there are n objects on the screen. Since there may be up to 50 objects on the screen at once, this could be as much as 2500 collision checks per frame = 50,000 collision checks per second. Each collision method calls the getHeight () and getWidth () methods several times. Unless they are very fast, I might not be able to use this in my program.
    Thank you for all your help.

    Can anyone tell me how fast the Image class'
    getHeight () and getWidth () methods are? Do these
    do some sort of complicated analysis on the picture,
    or do they simply return a variable that Java
    computes when the image is created?Considering Image is abstract and there's nothing in the contract about performance requirements nobody can answer this. It depends on the implementation. Generally, it's going to return very quickly and isn't going to require any kind of analysis at runtime.
    Here's the thing: I'm making a game. In this game,
    there are a lot of collisions. I check every object
    for collision with every other object. Thus I have
    about n^2 collision checks if there are n objects on
    the screen. Since there may be up to 50 objects on
    the screen at once, this could be as much as 2500
    collision checks per frame = 50,000 collision checks
    per second. Each collision method calls the
    getHeight () and getWidth () methods several times.
    Unless they are very fast, I might not be able to
    use this in my program.Then use a specific implementation you know is fast, or don't use the image directly.

  • Problems with getWidth() and getHeight() in class Canvas

    Hi,
    i am developing MIDlets with Sun Studio4 One Update1 (Mobile Edition). Here is a simple example Code for my Problem:
    class MyCanvas extends Canvas
        public void paint(Graphics g)
            //Clear the Display
            g.setColor(0,0,0); //black
            g.fillRect(0,0,getWidth(),getHeight());
    }If i try to execute the Program with the Default Color Phone emulator included with Suns WTK2.0, everything works fine. (Ive tried to print out the results of getWidth() and getHeight() on the console, everything ok, the Displays width and height is displayed.).
    The problem is, that any other emulator from WTK1.0.4_01 (included with Sun Studio4 ME) compiles and preverifies fine, but while running the application, the emulator quits with the following error:
    ALERT: No such method getWidth.()I
    Execution completed successfully
    Anyone has an idea?
    Thanks!!

    Hello,
    I'm having the exact same problem and I'd like to know what changes you made to your code to get it working. My class is not an inner class and is very much like yours and so follows the form:
    class MyCanvas extends Canvas{ 
    int element = getWidth()/10;
    public void paint(Graphics g) {        //Clear the Display  
    g.setColor(0,0,0); //black
    g.fillRect(0,0,getWidth(),getHeight());
    I am also using WTK104. I did not have this problem until I renamed my file. I carried the renaming throughout the rest of the file in a consistent fashion and I don't see any problems with it. Any help appreciated.

  • How can I create a single background image for a BorderLayout?

    I can create a background with an image file for the individual panel (North, West, Center, East and South) in a BorderLayout, but I've been spinning my wheel for a long while now trying to figure out how to create just one background with a single image file for all of these panels?
    In my application, a panel may contain various buttons, a listbox, a group of checkboxes, a combo box, or a canvas. Even if I used the same image file, when the panels are finally put together, one can clearly see that the end product is the result of a lot of patch works.
    Hope someone has an answer for this. BTW, I'm using AWT because it works with existing browsers without the need for a separate Java plug-in.
    Regards,
    V.V.

    Look at this :
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.awt.image.BufferedImage;
    public class PanI extends Frame
         Image map;
         Panel pan;
         myPan p8,p4,p6,p2,p5;
         BufferedImage I;
    public PanI() 
         addWindowListener(new WindowAdapter()
        {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);}});
         map = getToolkit().getImage("map2.gif");
         MediaTracker tracker = new MediaTracker(this);
         tracker.addImage(map,0);
         try   {tracker.waitForID(0);}
         catch (InterruptedException e){}
         I = new BufferedImage(1,1,BufferedImage.TYPE_INT_ARGB);
         setBounds(10,10,map.getWidth(null)+8,map.getHeight(null)+27);
         setLayout(new BorderLayout());
         pan = new Panel();
         add(pan,BorderLayout.CENTER);
         pan.setLayout(new BorderLayout());
         pan.setSize(map.getWidth(null),map.getHeight(null));
         p5 = new myPan(5);
         p5.setBackground(Color.red);
         pan.add(p5,BorderLayout.CENTER);
         p8 = new myPan(8);
         p8.setBackground(Color.orange);
         pan.add(p8,BorderLayout.NORTH);
         p4 = new myPan(4);
         p4.setBackground(Color.blue);
         pan.add(p4,BorderLayout.WEST);
         p6 = new myPan(6);
         p6.setBackground(Color.green);
         pan.add(p6,BorderLayout.EAST);
         p2 = new myPan(2);
         p2.setBackground(Color.pink);
         pan.add(p2,BorderLayout.SOUTH);
         setVisible(true);
    public class myPan extends Panel
         int where;
    public myPan(int i)
         super();
         where = i;
    public void paint(Graphics g)
         if (I.getWidth(null) != pan.getWidth() || I.getHeight(null) != pan.getHeight())
              I = new BufferedImage(pan.getWidth(),pan.getHeight(),BufferedImage.TYPE_INT_ARGB);
              Graphics      G = I.getGraphics();
              G.drawImage(map,0,0,pan.getWidth(),pan.getHeight(),null);     
              G.dispose();
         int x1=0;
         int x2=getWidth();
         int y1=0;
         int y2=getHeight();
         if (where == 8)
         if (where == 2)
              y1 =  p8.getHeight()+p5.getHeight();
              y2 =  getHeight()+y1;
         if (where == 4)
              y1 =  p8.getHeight();
              y2 =  y1+getHeight();
         if (where == 5)
              x1 =  p4.getWidth();
              x2 =  x1+getWidth();
              y1 =  p8.getHeight();
              y2 =  y1+getHeight();
         if (where == 6)
              x1 =  p4.getWidth()+p5.getWidth();;
              x2 =  x1+getWidth();
              y1 =  p8.getHeight();
              y2 =  y1+getHeight();
         g.drawImage(I,0,0,getWidth(),getHeight(),x1,y1,x2,y2,null);
    public void update(Graphics g)
         paint(g);
    public static void main (String[] args) 
         new PanI();
    Noah

  • Error while iserting a image in DB!!!!!

    Hello guys,
    I want to insert an image in the DB(MySql). I receive a compiling error when i try to insert an image.
    I tried to find in the forums.. but i could not find it..
    here is my code..
    public void insertImage(String name, String path){
              try{
         ImageIcon icon = new ImageIcon(path);
         Image image = icon.getImage();
            BufferedImage bImage = new BufferedImage(image.getWidth(null),image.getHeight(null),BufferedImage.TYPE_INT_RGB);
            Graphics bg = bImage.getGraphics();
            bg.drawImage(image,0,0,null);
            bg.dispose();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(bImage,"jpeg",out);
            byte[] buf = out.toByteArray();
            ByteArrayInputStream inStream = new ByteArrayInputStream(buf);
              try {
              String query = "insert  into instimage(Name, Image) values ('"+name+"',?)";
              PreparedStatement ps = conn.prepareStatement(query);
              ps.setBinaryStream(1,inStream,inStream.available());
              int count = ps.executeUpdate(query);
              }catch (SQLException e) {
                   e.printStackTrace();
              }     catch (Exception e) {
                   e.printStackTrace();
         The error is
    com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax;
    check the manual that corresponds to your MySQL server version for the right syntax to use near '?)' at line 1I would be grateful, if u guys help me out!!
    Thanks
    Edited by: frenchiee on Aug 27, 2008 8:16 AM

    Your query looks like valid. But only if the name variable has good value. If name has value "name with apostrophe'", your code will fail. Try
    String query = "insert into instimage(Name, Image) values (?,?)";
    PreparedStatement ps = conn.prepareStatement(query);
    ps.setString(1,name);
    ps.setBinaryStream(2,inStream,inStream.available());

  • How to tint a JPanel that paints an Image

    Hello all,
    I have a basic understanding of Java Swing architecture and the Drawing capabilities of the Graphics and Graphics2D classes. However, i am utterly confused how to implement a basic tint over an image.
    Overview:
    I have a GCard (Graphical Card) class that extends JPanel. This class contains a BufferedImage so that when the GCard is added to a higher-level Container, it paints the BufferedImage. What I want to do is tint that card image to a user specified color (let's say RED) via the GCard.setTint(Color.RED) method and then allow them to control if the tint is on/off via the GCard.setTinted(true) method.
    What I have:
    Currently, I have the following in my GCard.paintComponent(Graphics g) method:
         @Override
         protected void paintComponent(Graphics g) {
              int xPosition = 0;
              int yPosition = 0;
              if(image != null) {
                   g.drawImage(image, xPosition, yPosition, null);
                   if(isTinted() && tint != null) {
                        g.setColor(tint);
                        for(int x = xPosition; x < (xPosition + image.getWidth()); x += 2)
                             for(int y = yPosition; y < (yPosition + image.getHeight()); y += 2)
                                  g.drawLine(x, y, x, y);
         }All this does is implement a rudimentary tinting scheme by setting every other pixel in the panel to the tint color.
    What I want:
    What I'd like to see instead is a red haze over the entirety of the image. Much like the multiple item selection process that occurs when you select multiple things in a modern-day OS.
    How can i do this?
    From what I've read/thought out, I can either edit the actual image data to increase the level of the appropriate tint color, but I would prefer to be non-destructive to the image I'm holding in memory. I would prefer to imitate the 'layer' functionality of Adobe Photoshop where my image is the 'background' and I have a transparent panel that is tinted which can be switched on and off. Can I accomplish all of this in the paintComponent() method or will i need to add a JPanel (let's call it a tintPanel)to the GCard object and then add/remove that component from the GCard as necessary?
    Thanks for the help!
    -Pheez

    Something likeprotected void paintComponent(Graphics g) {
       super.paintComponent(g);
       g.drawImage(....);
       g.setColor(new Color(r, g, b, a)); // where a <1.0
       g.fillRect(aRectThatOverlapsTheImage);
    }db

  • PNG image returning null

    I can't for the life of me figure out what is wrong with the following code:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class CTFMain extends JPanel
        BufferedImage tileset;
        CTFMain()
            super();
            int width = 400;
         int height = 400;
         setPreferredSize(new Dimension(width, height));
            try
                //tileset = Toolkit.getDefaultToolkit().createImage("images\\EnvironmentTile.png");
                tileset = ImageIO.read(new File("images\\EnvironmentTile.png"));
            catch(IOException e)
        public void tic()
            repaint();
            System.out.println(tileset.toString());
        @Override
        public void paintComponent(Graphics g)
            g.setColor(Color.white);
            g.fillRect(0, 0, getWidth(), getHeight());
            g.setColor(Color.red);
            g.fill3DRect(20, 30, 150, 350, true);
            if(tileset == null)
                System.out.println("it's null");
            else
                g.drawImage(tileset, 0, 0, this);
        public static void main(String[] args)
            JFrame frame = new JFrame("Capture the Flag");
            CTFMain game = new CTFMain();
            frame.add(game);
            frame.pack();
            frame.setResizable(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
            while(true)
                game.tic();
                try
                    Thread.sleep(1000/33);
                catch(Exception e)
    }Whenever I run the program, tileset gets assigned a null value, even though the path file is there, so when it calls drawImage, it draws a blank picture. What am I doing wrong?
    Note: The println and fill3DRect statements are there to test if those methods are working, and they are.

    Abion47 wrote:
    Do you need that? <DWS>No, I just made that comment because I like reading back what I wrote. It amuses me.</DWS>
    Yes, I need the information.
    .. Because I don't know how to do that...Then it looks like you are stuffed, unless you can either do some research into the 'Java SDK Jar tool' and/or ask a smart question.

Maybe you are looking for

  • Unable to use j2ee -stop or the deploytool

    I am a J2EE newbie. I have recently installed j2sdkee1.3.1 on Windows XP. The J2SDK version I am using is j2sdk1.4.0_01. I can start the J2EE server successfully and view http://localhost:8000/index.html. However, I am unable to stop the server using

  • How Actual hours for a Particular Activity is getting Calculated in CJ20N?

    Hi Experts,          i have a small issue in PS module.In Cj20n after creation of project, under the activity the actual hours are differing from those of CATS hours.How or from where the actual hours are getting populated.The value is getting stored

  • Backint failed "ERROR: unable to find file "

    Hello I try to backup Oracle database 10.2 with netbackup tools on Redhat 2.6.18-53 I got errror: BR0231E Backup utility call failed ERROR: unable to find file /oracle/BWP/sapdata4 Can u help me Regards Fethi

  • Gulp, Parse error at '- \",\"//'  How do I Fix this?

    Hi, I'm trying to get Flex and OpenX to work together. Unfortunately, I get an XML parser error when viewing the site. So, in order to recreate the problem on my local machine, I changed my function and hard-coded the ad as adReturn. I get parse erro

  • Adobe PDF Plugin not working FireFox and SeaMonkey

    Just updated to Acrobat XI. I find that the plugin to view PDF's doesn't work. just receive a Blank Screen when I try to view a Plugin. I also notice in addons  when you go to plugins it shows two acrobat Pdf Plugins: Adobe Acrobat NPAI Plugin Adobe