如何在Java Applets中设置背景图像?
假设我想将background.gif作为我的java applet类的背景但是我该怎么做?
答案 0 :(得分:4)
我认为没有这样做的功能。但是您可以扩展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;
}
}