Java Applets中的背景图像

如何在Java Applets中设置背景图像?

假设我想让background.gif成为我的Java applet类中的背景,但是我该怎么做呢?

解决方法:

我不认为有功能可以做到这一点.但是您可以扩展面板(可以充当简单的组件容器),并覆盖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;    
     }
}
上一篇:如何将简单的Java游戏放入窗口(小程序)


下一篇:浏览器未显示Java小程序