Andreascopp
Andreascopp

Reputation: 113

How can I set an image in the background with java swing using ImageIcon?

I'm trying to create a GUI for "Connect Four" with java swing but can't figure out how I can set the play field that will be filled up with the pawns(sorry if it isn't the right word but I'm Italian). Could anyone help me out?

Upvotes: 0

Views: 484

Answers (1)

Oneiros
Oneiros

Reputation: 4378

You need to create a custom JPanel:

class BackgroundPanel extends JPanel {
    private BufferedImage image;

    public BackgroundPanel() {
        URL resource = getClass().getResource("background.jpg");
        try {
            image = ImageIO.read(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, this);
    }
}

and add it to your JFrame

Upvotes: 1

Related Questions