【问题标题】:Background Images in Java AppletsJava Applet 中的背景图像
【发布时间】:2011-09-03 14:05:49
【问题描述】:

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

假设我希望 background.gif 成为我的 java 小程序类中的背景,但我该怎么做呢?

【问题讨论】:

  • “如何在 Java Applets 中设置背景图像?” 获得图像后,就像在 JPanel 中一样。

标签: java image background applet


【解决方案1】:

我认为没有功能可以做到这一点。但是你可以扩展一个 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;    
     }
}

【讨论】:

  • AWT? (查看手表-意识到不戴手表)这是什么千年?
  • setSize(300,300); 这在浏览器中无法可靠运行。小程序的大小应由 HTML 设置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-26
  • 2023-03-04
  • 2012-08-04
  • 2011-11-23
  • 2021-08-07
相关资源
最近更新 更多