JPanel上的透明背景图像



我已经成功上传了一张图像作为JPanel的背景,但我不知道如何让JPanel子对象适合它。例如,当我添加按钮或复选框时,它们的表面就会出现。如何在没有矩形的情况下将按钮添加到jpanel(以图像为背景(。这是我的代码:

public class BackgroundPanel extends JPanel{
    BufferedImage backgroundImage;
    public BackgroundPanel() throws Exception
      {
        // load background image
        backgroundImage=javax.imageio.ImageIO.read(new java.io.File("/home/imanopholist/Bureau/bg17.jpg"));
        // set the panel size to the dimension of the background image
        int panelWidth=backgroundImage.getWidth(null);
        int panelHeight=backgroundImage.getHeight(null);
        setPreferredSize(new java.awt.Dimension(panelWidth,panelHeight));
      }
     public void paintComponent(java.awt.Graphics gr)
      {
        gr.drawImage(backgroundImage,0,0,null);
      }
     }
         // My panel :
          try {
            bgpanel=new BackgroundPanel();
            bgpanel.setLayout(null);
            bgpanel.setPreferredSize(new Dimension(785, 595));
            pan1.add(bgpanel);
            bgpanel.setVisible(true);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // My Label
        JLabel lblNbrServices = new JLabel("Number of Services");
        lblNbrServices.setFont(new Font("Tahoma", Font.BOLD, 12));
        lblNbrServices.setBounds(500, 110, 145, 29);
        bgpanel.add(lblNbrServices);

[接口]

可以使用BasicPanelUI来完成。创建一个这样的

BasicPanelUI UI = new BasicPanelUI() {
    @Override
    public void paint(Graphics g, JComponent c) {
        g.drawImage(backgroundImage,0,0,null);                
    }
};

并像这个一样连接到您的JPanel

this.setUI(UI);

可以添加其他组件而不会出现任何问题

最新更新