Java小程序中的背景图像

问题描述:

如何在Java小程序中设置背景图像?Java小程序中的背景图像

假设我想background.gif作为我的java applet类中的背景,但我该怎么做?

+0

*“你如何在Java小程序中设置背景图像?”*一旦拥有了图像,就像在“JPanel”中做的那样。 –

+0

顺便说一句 - GIF动画? –

我不认为有这样做的功能。但是你可以扩展一个Panel(它可以作为一个简单的组件容器)并且覆盖paint方法在后台绘制图像。

以下是一个示例程序。希望这可以帮助。

import java.applet.*; 
import java.awt.*; 
import java.net.*; 
import java.io.IOException.*; 

public class BackgroundApplet extends Applet { 
    Image backGround; 

    public void init() { 

      // set the size of the applet to the size of the background image. 
      // Resizing the applet may cause distortion of the image. 
      setSize(300, 300); 

      // Set the image name to the background you want. Assumes the image 
      // is in the same directory as the class file is 
      backGround = getImage(getCodeBase(), "save.GIF"); 
      BackGroundPanel bgp = new BackGroundPanel(); 
      bgp.setLayout(new FlowLayout()); 
      bgp.setBackGroundImage(backGround); 

      // Add the components you want in the Applet to the Panel 
      bgp.add(new Button("Button 1")); 
      bgp.add(new TextField("isn't this cool?")); 
      bgp.add(new Button("Useless Button 2")); 

      // set the layout of the applet to Border Layout 
      setLayout(new BorderLayout()); 

      // now adding the panel, adds to the center 
      // (by default in Border Layout) of the applet 
      add(bgp); 
    } 
} 

class BackGroundPanel extends Panel { 
    Image backGround; 

    BackGroundPanel() { 
      super(); 
    } 

    public void paint(Graphics g) { 

      // get the size of this panel (which is the size of the applet), 
      // and draw the image 
      g.drawImage(getBackGroundImage(), 0, 0, 
       (int)getBounds().getWidth(), (int)getBounds().getHeight(), this); 
    } 

    public void setBackGroundImage(Image backGround) { 
      this.backGround = backGround;  
    } 

    private Image getBackGroundImage() { 
      return backGround;  
    } 
} 
+2

AWT? (支票表 - 实现不佩带表)这是什么千禧年? –

+1

'setSize(300,300);'这在浏览器中无法可靠运行。 applet的大小应该由HTML设置。 –