2

The problem comes because I overwrite the paintComponent method of a jPanel, so when I repaint all the objets are hidden till I focus them. I need to overwrite the paintComponent method cause it's the only one answer I'd found in internet to change the background image of a jFrame.

So firstly I create a jPanel class:

    public class JPanelFondoPrincipal extends javax.swing.JPanel {

    public JPanelFondoPrincipal(){    
        this.setSize(800,500);
    }

    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        Dimension tamanio = getSize();
        ImageIcon imagenFondo = new ImageIcon(getClass().getResource("/images/fondo_principal.png"));        
        g.drawImage(imagenFondo.getImage(),0,0,tamanio.width, tamanio.height, null);        
        setOpaque(false);
    }
}

And in my jPanelForm:

private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
    // TODO add your handling code here:
    JPanelFondo p = new JPanelFondo();
    this.add(p);
    validate();
    p.repaint();
}

I'd already tried to add all my Objets (labels, textFields...) to a new Panel so I can add it after repaint, and set all the objets visibles manually but everything is still invisible.

Many thanks, I need to finish the app in 6 days and I'm getting crazy by the minute


EDIT: SOLVED THANKS TO CARDLAYOUT

Jose
  • 151
  • 1
  • 2
  • 6

2 Answers2

3

Swing programs should override paintComponent() instead of overriding paint().

http://java.sun.com/products/jfc/tsc/articles/painting/

And you should call super.paintComponent(g); first in overriden paintComponent();

   public void paintComponent(Graphics g){
        super.paintComponent(g);
        Dimension tamanio = getSize();
        ImageIcon imagenFondo = new ImageIcon(getClass().getResource("/images/fondo_principal.png"));        
        g.drawImage(imagenFondo.getImage(),0,0,tamanio.width, tamanio.height, null);        
        setOpaque(false);
    }

Here's the proper way to handle painting onto JPanel component.

Community
  • 1
  • 1
nullpotent
  • 9,162
  • 1
  • 31
  • 42
  • Thank you but after changing both things it still doesn't work :( Question code edited – Jose May 29 '12 at 17:12
3
  • don't add / remove JPanels or its contents on runtime, use CardLayout instead

  • your JPanelFondo p = new JPanelFondo(); doesn't corresponding somehow with public class JPanelFondoPrincipal extends javax.swing.JPanel {

  • for better help sooner edit your question with an SSCCE,

mKorbel
  • 109,525
  • 20
  • 134
  • 319