2012-02-21 14 views
-1

イメージをアプレットに追加しようとしています。私はこれを見つけましたが、わかりやすい例が見つかりませんでした。誰かが私が画像を追加してアプレットを追加する良い例がどこにあるか知っていますか?イメージをアプレットに追加する良い例を探しています

私はこれをオンラインにしましたが、アプレットを実行すると画像が表示されません。

public class Lab5 extends JApplet { 
     //Lab5(){} 


     Image img; 

     public void init() { 
       img = getImage(getDocumentBase(), "img\flag0.gif");     
     } 


     public void paintComponent(Graphics g) { 
      g.drawImage(img, 50, 50, this); 
     } 
} 

以下はここに私のHTMLファイル

<!DOCTYPE html> 
<html> 
    <head> 
     <title></title> 
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    </head> 
    <body> 
    <applet code="Lab5.class" width= 250 height = 50></applet> 
    </body> 
</html> 
+1

あなたが見たことのある多くの例があります。どのようなサイトを学習したのか、理解していない現在の例や具体的なコードについては、具体的な内容を教えていない限り、「良い」例を示すか、有益な助言を与えることはできませんあなたのために働いていて、あなたが見ている可能性のあるエラー。まともな答えを得ることを望むなら、この質問にもっと力を入れることを検討してください。 –

+1

まず、アプレットの作成方法に関するチュートリアルを読んでみましょう。 ImageIconとJLabelにイメージを置くことを検討してください。次に、JLabelにBorderLayoutなどのまともなレイアウトマネージャを与え、不透明にしてアプレットのcontentPaneにします。あるいは、JPanelの 'paintComponent()'メソッドでイメージを描画し、それをアプレットのcontentPaneにすることもできます。 –

+0

もう一度見ていきます。私はそれを私の授業の中からほぼそのまま取っておきました – Robert

答えて

5

あるインターネットからのURLから画像を示している簡単な例です。おそらく、このようなアプリケーションのjarファイルのディレクトリに保持された画像のように、インターネットURLの代わりにリソースを使用したい:

クラスSimpleAppletImage.java

import java.awt.image.BufferedImage; 
import java.io.IOException; 
import java.net.MalformedURLException; 
import java.net.URL; 
import javax.imageio.ImageIO; 
import javax.swing.*; 

@SuppressWarnings("serial") 
public class SimpleAppletImage extends JApplet { 
    @Override 
    public void init() { 
     try { 
     SwingUtilities.invokeAndWait(new Runnable() { 
      public void run() { 
       try { 
        // you might want to use a file in place of a URL here 
        URL url = new URL("http://duke.kenai.com/gun/Gun.jpg"); 
        BufferedImage img = ImageIO.read(url); 
        MyPanel myPanel = new MyPanel(img); 
        getContentPane().add(myPanel); 
       } catch (MalformedURLException e) { 
        e.printStackTrace(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 
     } catch (Exception e) { 
     e.printStackTrace(); 
     } 
    } 
} 

クラスMyPanel.java

import java.awt.Dimension; 
import java.awt.Graphics; 
import java.awt.image.BufferedImage; 

import javax.swing.JPanel; 

@SuppressWarnings("serial") 
class MyPanel extends JPanel { 
    private BufferedImage img; 

    public MyPanel(BufferedImage img) { 
     this.img = img; 
     setPreferredSize(new Dimension(img.getWidth(), img.getHeight())); 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     if (img != null) { 
     g.drawImage(img, 0, 0, this); // corrected 
     } 
    } 
} 
+0

私たちは例外処理にはまだ得ていないが、このコードを理解するために私に数分かかるだろう。 – Robert

+0

@AndrewThompson:よく取られた点、感謝! –

+0

@Andrew - Mr. Hi Standards - Thompson:2回目の編集が完了しました。 –

関連する問題