Click here to Skip to main content
15,896,201 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
java is supposed to load an image file but doesn't loads

the code has the class files
DrawImage.java should load image
Board.java creates a board with width and height

What I have tried:

package gms;

import java.awt.EventQueue;
import javax.swing.JFrame;

public class DrawImage extends JFrame {

    public DrawImage() {

        initUI();
    }

    private void initUI() {

        add(new Board());

        pack();

        setTitle("uc");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
    }

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                DrawImage c = new DrawImage();
                c.setVisible(true);
            }
        });
    }
}

Board.java

package gms;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JPanel;

public class Board extends JPanel {

    private Image uc;

    public Board() {

        initBoard();
    }
   
    private void initBoard() {
       
        loadImage();
       
        int w = uc.getWidth(this);
        int h =  uc.getHeight(this);
        setPreferredSize(new Dimension(w, h));       
    }
   
    private void loadImage() {
       
        ImageIcon cu = new ImageIcon("jvm.png");
        uc = cu.getImage();       
    }

    @Override
    public void paintComponent(Graphics g) {

        g.drawImage(uc, 0, 0, null);
    }
}
Posted
Updated 20-Feb-17 23:52pm
v2

I suppose you have hit this (see here[^]): "When you specify a filename or URL to an ImageIcon constructor, processing is blocked until after the image data is completely loaded or the data location has proven to be invalid. If the data location is invalid (but non-null), an ImageIcon is still successfully created; it just has no size and, therefore, paints nothing".
 
Share this answer
 
cool, changed the file path now the image loads fine

thanks
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900