Invisible objects because repaint method - Java Swing

情到浓时终转凉″ 提交于 2019-12-11 04:02:34

问题


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


回答1:


  • 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,




回答2:


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.



来源:https://stackoverflow.com/questions/10803445/invisible-objects-because-repaint-method-java-swing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!