在Java小程序背景图片 [英] Background Images in Java Applets

查看:237
本文介绍了在Java小程序背景图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do you set a background image in Java Applets?

比方说,我想background.gif是在我的Java Applet类的背景,但我会怎么做呢?

Let's say I want background.gif to be the background in my java applet class but how would I do this?

推荐答案

我不认为有一个函数来做到这一点。但是你可以扩展面板(可作为组件的一个简单的容器采取行动),并覆盖paint方法在后台绘制图像。



下面是一个示例程序。希望这有助于。

I dont think there is a function to do this. But you can extend a Panel (which can act as a simple container of components) and override the paint method to draw an image in the background.

The following is a sample program. Hope this helps.

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小程序背景图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆