JPanel transparent background and display elements [duplicate]

社会主义新天地 提交于 2020-07-16 04:28:12

问题


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

**Can you make the image transparent or that the elements are not opaque (setOpaque (false)), even putting it to those elements does not work for me.

Why do some elements have rectangles encapsulating them in gray?**

Code:

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);
    }
}

When loading "RUN" the .java file appears to me as follows:

Originally the design is as follows:


回答1:


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

Don't override paint(). The paint method is responsible for painting the child components. So your code paints the child components and then draws the image over top of the components.

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

protected 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.

Edit:

Read the entire section from the Swing tutorial on Custom Painting. The solution is to do the custom painting on a JPanel and then add the panel to the frame.

The content pane of a frame is a JPanel. So you will in effect be replacing the default content pane with your custom JPanel that paints the background image. Set the layout of your custom panel to a BorderLayout and it will work just like the default content pane.



来源:https://stackoverflow.com/questions/61871829/incorrect-dimensions-in-jpanel-image

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