JPanel

时间:2015-07-06 09:01:01

标签: java swing background

我已成功上传图片作为JPanel的背景,但我不知道如何让JPanel孩子适应它。例如,当我添加按钮或CHeckbox时,会出现它们的表面。 如何在没有该矩形的情况下将按钮添加到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);

[界面]

1 个答案:

答案 0 :(得分:0)

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

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

并附上JPanel这样的

this.setUI(UI);

可以毫无问题地添加其他组件