You cannot place a component inside an Image
. What you want to do is paint the Image
onto the background of a swing component (like JPanel
). All swing components have a paint()
method that calls these three methods (perhaps not quite this order): paintComponent()
, paintChildren()
, paintBorder()
. So, you want to override the paintComponent()
method to paint your background image over the panel. When this runs, your custom method will be called, and then the paintChildren()
method will be called, which will paint all "child" components over the top of your background image:
class BackgroundImagePanel extends JPanel {
public void setBackgroundImage(Image backgroundImage) {
this.backgroundImage = backgroundImage;
}
@Override
protected void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
graphics.drawImage(backgroundImage, 0, 0, this);
}
private Image backgroundImage;
}
BackgroundImagePanel panel = new BackgroundImagePanel();
panel.setBackgroundImage(image);
panel.add(new JTextField("Enter text here..."));
panel.add(new JButton("Press Me"));