user3341249
user3341249

Reputation: 73

Setting Loaded GIF as a Background

Situation: I have a JFrame and I have managed to import the GIF and display it in the Main Panel however it moves all of my other panels down, causing my GUI to be in disarray.

Question: How should I go about making the GIF the background instead of adding to the Main Panel Like I am doing?

Note: The code is simply making a Jframe ,setting it's details, adding the panels then displaying the GIF as a Jlabel. If you need the code I can display it below.

Upvotes: 2

Views: 5710

Answers (3)

Markus Millfjord
Markus Millfjord

Reputation: 707

UPDATED ANSWER

Now in accordance with Oracle's Swing UI-guidlines as correctly indicated by @MadProgrammer

Best way to add a background is to simply paint it. Create a BackgroundPanel (extends JPanel) and override paintComponent(...);

public class BgPanel extends JPanel
{ 
    //Overload and paint your background
    public void paintComponent(Graphics g)
    {
        //create image object, or more preferably do that in the BgPanel constructor
        g.drawImage(image, 0, 0, null);
    }
}

In accordance with Oracle's guidelines for custom rendering when using Swing.

Upvotes: 1

MadProgrammer
MadProgrammer

Reputation: 347314

There are several ways you might achieve this...

You could...

Use a JLabel, setting the label's icon property to the reference of the image. You could then apply a layout manager to the label and set the label as main container for the rest of you components by simply adding them to it as usual...

IconImage image = ...;
JLabel background = new JLabel(image);
background.setLayout(...);
// You could set the frames content pane to the label and keep
// working as per normal, adding components to the frame
setContentPane(background);
// or, simply add components to it directly like any other container
background.add(...);

The great thing about this, is if the GIF is animated, it will contain to play as normal...nice side effect. The draw back is, JLabel won't resize the image for you...

You could...

Paint the image to the background of the component, like JPanel and then add your remaining components to it.

This would allow you to apply special effects and or resize the image if you wanted to do. If it's an animated GIF however, this makes it extremely more complex, as you will need to animate the frames yourself.

Take a look at...

For more details

Upvotes: 2

DarkSil3ncer
DarkSil3ncer

Reputation: 1

You can do it in the style.css so this would be for the whole body.

body { background-position: center center; background-image: url('../images/MyGif.gif'); background-repeat: no-repeat; }

or create a class for it

.frame{ background-position: center center; background-image: url('../images/MyGif.gif'); background-repeat: no-repeat; }

Upvotes: 0

Related Questions