0

I understand that the following sets the background colour of the contentPane. How do I set a picture as its background instead?

I've tried these:

But none of them have worked.

JLabel lblbackground = new JLabel();
lblbackground.setBounds(20, 20, 160, 160);
lblbackground.setBorder(new LineBorder(new Color(0, 0, 0), 2));
lblbackground.setIcon (new ImageIcon (this.getClass().getResource("/boundary/background.jpg")));
lblbackground.setHorizontalAlignment (SwingConstants.CENTER);                   
BufferedImage img = new BufferedImage(lblbackground.getIcon().getIconWidth(), lblbackground.getIcon().getIconHeight(), BufferedImage.TYPE_INT_RGB);
Graphics g = img.createGraphics();
lblbackground.getIcon().paintIcon(null, g, 0, 0);
g.dispose();
Image newing = img.getScaledInstance(150, 150, java.awt.Image.SCALE_SMOOTH);
lblbackground.setIcon(new ImageIcon(newing));           

//getContentPane().setLayout(new GridBagLayout());
contentPane = new JPanel();
//contentPane.setBackground(Color.LIGHT_GRAY);
contentPane.setBorder(null);
contentPane.setLayout(null);        
contentPane.add(lblbackground);
setContentPane (contentPane);
Community
  • 1
  • 1
user2945412
  • 297
  • 1
  • 3
  • 13

1 Answers1

1
(...)
// 1) Create your image;
final ImageIcon image = new ImageIcon("../folder/myImage.gif");

//2) Create a JPanel with a background image;
  JPanel  myPanel = new JPanel(){
            @Override
            public void paintComponent(Graphics g)
            {
                g.drawImage(image.getImage(), 0, 0, null);
            }
    };

//3) Add panel 
getContentPane().add(myPanel);

(...)
Pedro Vítor
  • 191
  • 1
  • 6
  • thank you, but I cannot get to work yet. how do I set the contentPane then? – user2945412 Nov 07 '13 at 19:50
  • In your code, you are doing this: 'contentPane = new JPanel(); setContentPane (contentPane);' right? So, just get this contentPane and add another element there. This element can be a JButton, a JLabel, or just another JPanel, like explained in my code. Try to create this JPanel in your code and adding inside your. – Pedro Vítor Nov 07 '13 at 20:12
  • thank you but i had managed to get away with something even simpler, i appreciate it - setContentPane(new JLabel(new ImageIcon(PlaceOrder.class.getResource("/boundary/background.jpg")))); – user2945412 Nov 07 '13 at 20:22