1

I have a problem with my code, I'm farelly new to java programming but the thing is that I want to set a bg picture but the code that I use disapears everything else that I've put in the JFrame..

panel.setSize(950, 600);
panel.setTitle("Nuevo Usuario Otto's");
panel.setResizable(false);
panel.setLocationRelativeTo(null);
try {
    panel.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("C:\\CELLES_PROYECTO\\darkTrees.jpg")))));
} catch (IOException e) {

    e.printStackTrace();
}
panel.setResizable(false);
panel.pack();
panel.setVisible(true);
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Esteban Rincon
  • 2,040
  • 3
  • 27
  • 44

1 Answers1

0

JLabel does not support child components. Instead, use a JPanel for the content pane, and override its paintComponent method to draw the image.

try {
    final Image backgroundImage = ImageIO.read(new File("C:\\CELLES_PROYECTO\\darkTrees.jpg"));
    setContentPane(new JPanel(new BorderLayout()) {
        @Override public void paintComponent(Graphics g) {
            g.drawImage(backgroundImage, 0, 0, null);
        }
    });
} catch (IOException e) {
    throw new RuntimeException(e);
}

The above example also sets the JPanel's layout to BorderLayout, to match the default content pane layout.

Boann
  • 48,794
  • 16
  • 117
  • 146