Tomer
Tomer

Reputation: 231

Using JLabel for a background image

When I run the code it just opens an empty window I also important whatever is necessary

relevant parts of the code:

public class Game extends JFrame implements ActionListener,KeyListener{
    private JLabel background; 
....  
public Game(){
background=new JLabel(new ImageIcon("/graphics/board.gif"));
...
this.add(background);
this.setSize(800,600);
this.setVisible(true);...

I tried adding the JLabel to a JPanel and then add it to the frame but it still shows nothing in the window

Upvotes: 1

Views: 1349

Answers (3)

Java Devil
Java Devil

Reputation: 10959

Originally the code was:

JLabel background = new JLabel("/graphics/board.gif");

This would not set the image at the path described, Suggest that the following method is used (this could be simplified to just use a different JLabel constructor but steps shown for clarity)

Create and load the image and then set the icon for the Label As follows

ImageIcon icon = new ImageIcon("/graphics/board.gif"); 
JLabel background = new JLabel();
background.setIcon(icon);

Link to ImageIcon Java Doc

Upvotes: 2

camickr
camickr

Reputation: 324118

I'm guessing you have a directory structure something like:

-c:\java  
  - source (for source and class files)  
    - graphic (for your images)
background=new JLabel(new ImageIcon("/graphics/board.gif"));

Don't specify the leading "/" in the file name. That tells Java to look at the root of the C drive, not at the directory where your class is executing from.

Also, don't use:

this.setSize(800,600);

The image does not stretch to fill the size of the frame. Intead you should be using:

this.pack();

so the frame will be the size of the image.

Upvotes: 0

Jovo Krneta
Jovo Krneta

Reputation: 558

It is important to set in the layout the order in which the elements are displayed , maybe you have something that is displayed over the label..

Upvotes: 0

Related Questions