简体   繁体   中英

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) 在此处输入图片说明

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:-

在此处输入图片说明

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM