我正在尝试将图片添加到我的applet中。我用谷歌搜索了这个,但我没有找到一个我理解的体面的例子。有谁知道我在哪里可以找到一个添加图像和applet的好例子?
我在网上得到了这个,但是当我运行applet时它没有显示我的图像。
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>
答案 0 :(得分:5)
这是一个简单的示例,显示来自互联网的URL的图像。您可能在互联网网址中使用资源,例如应用程序jar的目录中保存的图像:
类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
}
}
}