JPanel透明背景和显示元素

I insert a background image into a JPanel but some interface elements disappear. The following Java Swing elements do not appear:

  • label_titulo
  • label_usuario
  • label_password
  • button_acceder

**您可以使图像透明还是元素不透明(setOpaque(false)),即使将其放在这些元素上对我也不起作用。

为什么某些元素具有以灰色封装的矩形?**

码:

public class InicioSesion extends javax.swing.JFrame{
    private Image imagenFondo;
    private URL fondo;

    public InicioSesion(){
        initComponents();

        try{
            fondo = this.getClass().getResource("fondo.jpg");
            imagenFondo = ImageIO.read(fondo);
        }catch(IOException ex){
            ex.printStackTrace();
            System.out.print("Imagen no cargada.");
        }
    }


    @Override
    public void paint(Graphics g){
        super.paint(g);
        g.drawImage(imagenFondo, 0, 0, getWidth(), getHeight(), this);
    }
}

加载“ RUN”时,.java文件对我显示如下:

enter image description here

最初的设计如下:

enter image description here

评论
  • mut
    mut 回复
    public void paint(Graphics g){
        super.paint(g);
        g.drawImage(imagenFondo, 0, 0, getWidth(), getHeight(), this);
    }
    

    不要覆盖paint()。绘制方法负责绘制子组件。因此,您的代码会绘制子组件,然后在组件上方绘制图像。

    Instead, for custom painting of a component you override the paintComponent() method:

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.drawImage(imagenFondo, 0, 0, getWidth(), getHeight(), this);
    }
    

    Read the section from the Swing tutorail on A Closer Look at the Paint Mechanism for more information.