请问:
   在GUI程序设计中,能否将图片作为背景加入JFrame,然后在上面加一些JPanl,JButton之类的?

解决方案 »

  1.   

    getContentPane()添加一个JLayeredPane, Layer里面添加一个JLabel在最下层, 默认层上增加你需要的东西, 图片放在JLabel里.
      

  2.   

    在frame上加panel,重载panel的paintComponent方法,把加入按钮的过程放在panel的构造方法中。代码如下:import java.awt.Graphics;
    import java.awt.Image;
    import java.io.File;
    import java.io.IOException;import javax.imageio.ImageIO;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;public class ImageTest { /**
     * @param args
     */
    public static void main(String[] args) {
    ImageFrame frame = new ImageFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    }}class ImageFrame extends JFrame
    {
    public ImageFrame()
    {
    setTitle("ImageTest");
    setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

    // add panel to frame
    ImagePanel panel = new ImagePanel();
    getContentPane().add(panel);
    }

    public static int DEFAULT_WIDTH = 300;
    public static int DEFAULT_HEIGHT = 200;
    }class ImagePanel extends JPanel
    {
    public ImagePanel()
    {
    // acquire the image try {
    img = ImageIO.read(new File("F:/files/pic/My Pictures/dog/4.jpg"));
    } catch (IOException e) {
    e.printStackTrace();
    }

    JButton btn = new JButton("test");
    add(btn);

    }
    public void paintComponent(Graphics g)
    {
    super.paintComponent(g);

    if (img == null)return;

    int imgWidth = img.getWidth(this);
    int imgHeight = img.getHeight(this);

    // draw the img in the top left corner

    g.drawImage(img, 0, 0, null);
    // tile the img acrose the panel

    for (int i = 0;i * imgWidth <= getWidth(); i++)
    for (int j = 0; j * imgHeight <= getHeight(); j++)
    if (i + j > 0)
    g.copyArea(0, 0, imgWidth, imgHeight,
    i * imgWidth, j * imgHeight);

    }

    private Image img;
    }