简体   繁体   中英

Set an image as background to JFrame

I am making a small app, but i want to set an image as background at the whole window. I tried to make this like below but nothing happen. The image is in the folder where the class is so as a path I put only the name...Can you help me please? what can I do?

Container c = getContentPane();
  setContentPane(c);
   setContentPane(new JLabel(new ImageIcon("Chrysanthemum.jpg")));

One possibility is to add a BorderLayout to the JFrame, which should fill the JFrame with the JLabel , then set the background, adding the JLabel to the frame and then add components to it, like this:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Foo extends JFrame {

    public Foo() {
        setLayout(new BorderLayout());


JLabel background = new JLabel(new ImageIcon("Untitled.png"));
    add(background);
    background.setLayout(new FlowLayout());
    background.add(new JButton("foo"));
    setSize(500, 500);
    setVisible(true);
}

public static void main(String[] args) {
    Foo foo = new Foo();
}
}

The above works for me, with the JButton at the top center of the 500 by 500 JFrame with the specified background.

What I would do is create a JPanel with a background image, and add it to the JFrame . I already have a BackgroundPanel class right in one of my projects, and this is the setup I have for it.

public class MyFrame extends JFrame {

    private BackgroundPanel bgPanel;

    public MyFrame() {
        bgPanel = new BackgroundPanel("Chrysanthemum.jpg");

        setTitle("MyFrame");
        setResizable(false);
        setContentPane(bgPanel);
        pack();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args) {
        new MyFrame();
    }
}

// -- BackgroundPanel class

public class BackgroundPanel extends JPanel {
    private static final long serialVersionUID = 1L;

    private Image bg;

    public BackgroundPanel(String path) {
        this(Images.load(path).getImage());
    }

    public BackgroundPanel(Image img) {
        this.bg = img;
        setPreferredSize(new Dimension(bg.getWidth(null), bg.getHeight(null)));
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (bg != null) g.drawImage(bg, 0, 0, getWidth(), getHeight(), null);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM