[java] Problems with Image
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.
Hookflash
// Test.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class DisplayPanel extends JPanel
{
DisplayPanel()
{
setBackground(Color.white);
ball = Toolkit.getDefaultToolkit().getImage("./test.gif");
setPreferredSize(new Dimension(320, 240));
}
public void paintComponent(Graphics g)
{
super.paintComponent(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
{
Test()
{
super("Test");
getContentPane().add(new DisplayPanel(), "Center");
pack();
}
public static void main(String[] args)
{
Test test = new Test();
test.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
test.show();
}
}
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.
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement