JPanel image won't show

I have one class that extends JFrame. The code is as below...

import java.awt.*;

import java.awt.Component;

import java.awt.Container;

import java.awt.event.WindowEvent;

import java.awt.event.WindowListener;

import java.awt.event.WindowStateListener;

import javax.swing.*;

publicclass NewGameextends JFrame

{

private JPanel gamearea =new JPanel();

private Beer beer=new Beer();

private Container c;

static JFrame window =new NewGame();

public NewGame()

{

gamearea.add(beer);

c = getContentPane();

c.setLayout(new BorderLayout());

c.add(gamearea, BorderLayout.WEST);

c.setSize(480, 480);

//... Set window characteristics

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setTitle("Game");

pack();

setVisible(true);

}

publicstaticvoid main(String[] args)

{

window.setVisible(true);

}

}

And another class that extends the JPanel...

import javax.swing.*;

import java.awt.*;

import java.util.*;

import java.awt.event.KeyEvent;

import java.awt.event.KeyListener;

publicclass Beerextends JPanelimplements KeyListener

{

Image bg = Toolkit.getDefaultToolkit().getImage("res/pub.jpg");

public Beer()

{

this.setPreferredSize(new Dimension(480, 480));

this.addKeyListener(this);// This class has its own key listeners.

this.setFocusable(true);// Allow panel to get focus

}

publicvoid paint(Graphics g)

{

g.drawImage(bg,0,0,null);

}

publicvoid keyTyped(KeyEvent e){}

publicvoid keyPressed(KeyEvent e)

{

System.out.println("ok");

}

publicvoid keyReleased(KeyEvent e)

{

}

}

Both this classes compiles fine. But when execute, the image in the JPanel class wont show. I have to minimize the JFrame den maximize it to show the image. why is this strange thing is happening?

[4225 byte] By [Hanz_05a] at [2007-11-27 7:54:09]
# 1
Instead of WEST try CENTER and if then also dont work then you have to make layout null and then setBounds of your panel
student@sunDNa at 2007-7-12 19:35:25 > top of Java-index,Java Essentials,Java Programming...
# 2

Swing related questions should be posted in the Swing forum.

> why is this strange thing is happening?

The image isn't loaded when the frame is displayed. You need to notify the panel to repaint itself when the image is loaded:

//g.drawImage(bg,0,0,null);

g.drawImage(bg,0,0,this);

Some other comments:

a) you should be overriding paintComponent(...) not paint(...) for custom painting

b) Your NewGame class is a JFrame so it doesn't make sense to define a static variable in the class. Get rid of that variable and then use:

//window.setVisible(true);

new NewGame();

camickra at 2007-7-12 19:35:25 > top of Java-index,Java Essentials,Java Programming...
# 3
Thanks...I changed the image parameter from null to this. It works...
Hanz_05a at 2007-7-12 19:35:25 > top of Java-index,Java Essentials,Java Programming...