-2

I am trying to add a background image to a JPanel. I have tried using a JLabel however when I tried it this way I wasn't able to add buttons over the top of the image.

In IntelliJ the gui builder code is hidden and most other tutorials utilize this generated code.

How would this be achieved using IntelliJ's gui builder?

Sam J
  • 1
  • Possible duplicated of [How to add an image to a JPanel?](https://stackoverflow.com/questions/299495/how-to-add-an-image-to-a-jpanel) – Abe Mar 05 '18 at 14:17

1 Answers1

0

Images can be incorporated fairly easily into a JFrame/JPanel using this ImageComponent-class (you can handle it just like any other component) :

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.*;

class ImageComponent extends Component {

    BufferedImage img;

    public void paint(Graphics g) {
        g.drawImage(img, 0, 0, null);
    }

    public ImageComponent(String path) {
       try {
           img = ImageIO.read(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Dimension getPreferredSize() {
        if (img == null) {
            return new Dimension(100,100);
        } else {
            return new Dimension(img.getWidth(), img.getHeight());
        }
    }
}
hensing1
  • 187
  • 13