2011-09-03 86 views
3

如何在Java小程序中設置背景圖像?Java小程序中的背景圖像

假設我想background.gif作爲我的java applet類中的背景,但我該怎麼做?

+0

*「你如何在Java小程序中設置背景圖像?」*一旦擁有了圖像,就像在「JPanel」中做的那樣。 –

+0

順便說一句 - GIF動畫? –

回答

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;  
    } 
} 
+2

AWT? (支票表 - 實現不佩帶表)這是什麼千禧年? –

+1

'setSize(300,300);'這在瀏覽器中無法可靠運行。 applet的大小應該由HTML設置。 –