开发者

How to render a 2d image in Java

I have a quick question about Java. I'm sorry if this question is really basic, but I'm a beginner Java programmer :D

I want to render a 2d image in a window, but I can't figure it out. I've looked at the graphics API here:

http://download.oracle.com/javase/1.4.2/docs/api/java/awt/Graphics.html

and the only method I could find that might work is drawImage(). It wasn't working for me, though, but maybe it has to do with the ImageObserver Observer parameter? I just put null for that following some tutorial I found somewhere, but I still get a compile error: Here is my paint method:

public void paint(Graphics g)
{   
    Image img1 = Toolkit.getDefaultToolkit().getImage("theImage.png");
    g.drawImage(img1, 100, 100, null);
} // public void paint(Graphics g)

and here are the methods that call it:

public static void main(String[] args)
{
    MyGame game = new MyGame();
    game.setVisible(true);
    game.play();      

} // public static void main(String[] args)



/** The play method is where the main game loop resides. 
 */
public void play()
{
    boolean playing = true;
    //Graphics g = new Graphics();
    while (playing)
    {
        paint();
    }

} //  public void play()

The thing is when I call paint in the while loop, I get this error: paints(java.awt.Graphics) in MyGame cannot be applied to ()

What does that mean? How can I fix it so I can successfully render a 2d image?

Than开发者_如何转开发ks in advance :D


Instead of paint(); use repaint();


You should be overriding paintComponent(Graphics g). Also, as @TotalFrickinRockstarFromMars suggested, you should be invoking repaint().


  • You overrid the paintComponent(Graphics g)

class Game extends JComponent { // Your game class

Image img = null;

public Game() {
   img = getImage("/theImage.png");
}

private Image getImage(String imageUrl) {

try {

    return ImageIO.read(getClass().getResource(imageUrl));

} catch (IOException exp) {}

return null;

}

paintComponent(Graphics g) {

   g.drawImage(img, 100, 100, null);

}

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜