0

I have set the background on my Jframe with ImageIO and a repaint( drawImage).It works. My JFrame is a JFrame form. When I add more components by dragging them on the Jframe and I run the project, the JFrame display only the first component that I added. The other components are displayed only when I moved the mouse on them. Help???

class Main extends JFrame { 

BufferedImage img = null;

Main() {

       try {
          img = ImageIO.read(new File("sfondo.jpg"));
       }  catch (Exception e) {

       }

       this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       initComponents(); 
       this.repaint();
       setVisible(true);
}

@Override
public void paint(Graphics g) {
       g.drawImage(img, 1, 1, null);

}
@SuppressWarnings("unchecked")


public static void main(String[] args) {

       Main jrframe = new Main();

}
Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60
  • 1
    pls use paintComponent instead of paint. Also call there as first thing super.paintComponent. Probably not the source of the problem, but potentially the source of other future problems – Terry Storm Oct 24 '14 at 10:04
  • 2
    Don't override `paint` of top level containers, what do you think is painting the components? Actually, just go have a look at [this question](http://stackoverflow.com/questions/26545536/how-do-you-use-an-image-as-background-and-place-an-image-in-front-of-that?noredirect=1#comment41714318_26545536) which demonstrates a concept for painting an image in the background. You can set the `JPanel` as the frames content pane and just add stuff to the frame as per normal if you wanted to – MadProgrammer Oct 24 '14 at 10:04
  • @TerryStorm Again, extending from `JFrame` - no `paintComponent` method :P – MadProgrammer Oct 24 '14 at 10:05
  • and again, you are right ;) – Terry Storm Oct 24 '14 at 10:07
  • Thank you Terry Storm. But if I use super.paintComponent() my background will not be displayed .-. – Mattia Meccariello Oct 24 '14 at 10:13
  • A complete example is shown [here](http://stackoverflow.com/a/2658663/230513). – trashgod Oct 24 '14 at 10:38
  • A piece of code? Pls It isn't that I want to do – Mattia Meccariello Oct 24 '14 at 13:23

1 Answers1

0

@ initComponents() try to create a contentPane and add some components , e.g:

Container cp = getContentPane();

cp.add(component1);
Borja Coalla
  • 216
  • 1
  • 3
  • 11