将加载的GIF设置为背景

情况:我有一个JFrame ,我已经设法导入GIF并在主面板中显示它,但是它将我的所有其他面板向下移动,导致我的GUI处于混乱状态。

问题:我应该如何将GIF作为背景而不是像我一样添加到主面板?

注意:代码只是制作一个Jframe ,设置它的细节,添加面板然后将GIF显示为Jlabel 。 如果您需要代码,我可以在下面显示它。

有几种方法可以达到这个目的……

你可以…

使用JLabel ,将标签的图标属性设置为图像的参考。 然后,您可以将布局管理器应用于标签,并将标签设置为其他组件的主容器,只需像往常一样将它们添加到其中…

 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(...); 

关于这个的好处是,如果GIF是动画的,它将包含正常播放…很好的副作用。 退款是, JLabel不会为您调整图像大小…

你可以…

将图像绘制到组件的背景(如JPanel ,然后将其余组件添加到其中。

这将允许您应用特殊效果,或者如果您愿意,可以调整图像大小。 如果它是一个动画GIF,那么这会使它变得非常复杂,因为你需要自己动画帧。

看一眼…

  • 执行自定义绘画
  • 2D图形
  • 保持JPanel背景图像的纵横比

更多细节

更新的答案

现在按照@MadProgrammer正确指出的Oracle的Swing UI-guidlines

添加背景的最佳方法是简单地绘制它。 创建BackgroundPanel(扩展JPanel)并覆盖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); } } 

根据Oracle使用Swing时的自定义渲染指南。

你可以在style.css中做到这一点,这将是整个身体。

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

或者为它创建一个类

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