简体   繁体   中英

Java - JPanel can't draw background image

I am learning how to work with Gui's in java. Currently I'm trying to make a simple program that opens a Gui and draws an image to the background. The problem is that the background is completely white instead of the image.

Code:

Main.java:

package com.flaghacker.buckygame;

public class Main
{
    public static void main(String[] args)
    {
        GuiFrame guiFrame = new GuiFrame();
    }
}

GuiFrame.java:

package com.flaghacker.buckygame;

import javax.swing.JFrame;

public class GuiFrame extends JFrame
{
    private GuiPanel guiPanel;

    public GuiFrame()
    {
        //General
        super("Title");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Size
        this.setSize(1100, 650);
        this.setResizable(true);

        //Components
        guiPanel = new GuiPanel();
        this.add(guiPanel);

        //Final
        this.setVisible(true);
    }
}

GuiPane.java:

package com.flaghacker.buckygame;

import javax.swing.ImageIcon;
import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.Image;

public class GuiPanel extends JPanel
{
    private Image backGround;

    public GuiPanel()
    {
        backGround = new ImageIcon("D:\\Install\\Java Projects\\Testing\\Bucky\\Back.jpg").getImage();
    }

    @Override
    public void paint(Graphics g)
    {
        super.paint(g);
        g.drawImage(backGround, 0, 0, null);
    }
}

I test your code and it works ... the possible problem are two

first) your image isn't in

"D:\\\\Install\\\\Java Projects\\\\Testing\\\\Bucky\\\\Back.jpg"

i suggested you to use

"D:/Install/Java Projects/Testing/Bucky/Back.jpg"

and verify Case insensitive.

second) the image Back.jpg have width and height more high of 1100 650 so you display only a top left angle of image

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