JPanel的透明背景和显示元素[重复]。

问题描述 投票:0回答:1

我插入一个 背景想象变成 JPanel 但一些界面元素消失了。以下Java Swing元素没有出现。

  • label_titulo
  • label_usuario
  • label_password
  • 钮扣_accesser

**你能不能把图像变成透明的,或者说元素不是不透明的(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

java jpanel
1个回答
2
投票
public void paint(Graphics g){
    super.paint(g);
    g.drawImage(imagenFondo, 0, 0, getWidth(), getHeight(), this);
}

不要覆盖paint()。paint方法负责绘制子组件。所以,你的代码会画出子组件,然后在组件上面画出图像。

相反,对于组件的自定义绘制,你可以重写该方法。paintComponent() 办法 JPanel:

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

阅读《秋千教程》中的部分内容,内容如下 近距离观察涂装机制 以获取更多信息。

编辑。

阅读Swing教程的全部内容,请点击 Custom Painting. 解决方法是在JPanel上进行自定义绘画,然后将面板添加到框架中。

框架的内容窗格是一个JPanel。因此,你实际上将用你的自定义JPanel替换默认的内容面板,以绘制背景图片。将自定义面板的布局设置为 BorderLayout 它将像默认的内容窗格一样工作。

© www.soinside.com 2019 - 2024. All rights reserved.