I''m having trouble displaying an Image (I''m a newbie). The problem is that, when the app loads, no Image is displayed, and the ball''s width & height are both set to -1. If I resize the frame (or even just click on it), the image appears and the ball''s width and height are updated accordingly. I can''t figure this one out... Thanks in advance for your time and help.
class DisplayPanel extends JPanel
ball = Toolkit.getDefaultToolkit().getImage("./test.gif");
setPreferredSize(new Dimension(320, 240));
public void paintComponent(Graphics g)
g.drawString("Width: " + ball.getWidth(null) +
" Height: " + ball.getHeight(null), 10, 10);
int x = getWidth() / 2 - ball.getWidth(null) / 2;
int y = getHeight() / 2 - ball.getHeight(null) / 2;
g.drawImage(ball, x, y, null);
private Image ball;
class Test extends JFrame
getContentPane().add(new DisplayPanel(), "Center");
public static void main(String args)
Test test = new Test();
public void windowClosing(WindowEvent e)
A similar problem happened to me last weekend, an Image that I painted to a scroll pane would not appear untill I interacted with the mouse on the program. The solution is to call repaint() on the outermost container after you make a change to the scroll pane or JPanel.
The reason that your image is reporting -1 for the dimesions is that it is not loaded yet. Properly, you should use media tracker and wait for the Image to load. Unfortunately this seems like overkill to new programmers who just want to load one image. One work around is to do this: while (image.getWidth(null) == -1) ;
This will loop infinitely untill the image if fully loaded. After that I would call JFrame''s repaint() method just to be safe.