Setting Loaded GIF as a Background

前端 未结 3 917
时光取名叫无心
时光取名叫无心 2021-01-22 06:50

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

3条回答
  •  情歌与酒
    2021-01-22 07:22

    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...

    • Performing Custom Painting
    • 2D Graphics
    • maintaining aspect ratio of JPanel background image

    For more details

提交回复
热议问题