OldSchool
OldSchool

Reputation: 2183

what is the correct way of setting background image of a frame using JLabel?

Previously,i was using the following statement for setting the background of a frame

  JLabel backImage = new JLabel(new ImageIcon("C\\users\\BSK\\Desktop\\win.png"));

and it was working fine and produces the following result.(coding for buttons is not shown)enter image description here

But when i created new Package named Resource and put the image in that and uses following statements

JLabel backImage=new JLabel();
ImageIcon img;
img = new ImageIcon(getClass().getResource("/Resource/win.png"));
backImage.setIcon(img);

I get the following result:-

enter image description here

As you can see my puzzle box goes out of scope.So what is the difference between these two approaches?

EDIT Layout for JLabel backImage used is Border Layout.i am firstly setting the content pane of the JFrame as the JLabel which is backImage and adding the buttons in a separate pannel in GridBagLayout and then adding the pannel to the contentpane of the frame which is again the JLabel backImage.

Upvotes: 0

Views: 104

Answers (1)

trashgod
trashgod

Reputation: 205785

The location of the ImageIcon is determined by the layout manager of the frame's content pane, BorderLayout by default. Alternatively, override paintComponent() in the button panel. Invoke drawImage() on the supplied graphics context to render the image in the desired location and size. Add the button panel to the enclosing frame's content pane.

Upvotes: 1

Related Questions