这个小程序假设在彼此的顶部显示两张图片。当我在浏览器中运行这个小程序时,它不显示图片。图片名称正确,与小程序位于同一文件夹中。
import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
public class question3b extends JApplet{
public void init() {
repaint();
}
public void paint(Graphics g)
{
super.paint(g);
ImageIcon image1 = new ImageIcon("1.JPG");
ImageIcon image2 = new ImageIcon("2.JPG");
g.drawImage(image1.getImage(), 100, 20 , 100, 100, this);
g.drawImage(image2.getImage(), 100, 150 , 100, 100, this);
}
}
这是 HTML 页面。
<html>
<head>
<title>Welcome Java Applet</title>
</head>
<body>
<applet
code = "question3b.class"
width = 1000
height = 500>
</applet>
</body>
</html>
最佳答案
建议:
- 不要覆盖 JApplet 的绘制方法。
- 而是覆盖 JPanel 的 paintComponent 方法并在小程序中显示面板。
- 不要在 paintComponent 方法中调用 repaint()。请。
- 不要在 paint 或 paintComponent 方法中读入图像。仅一次阅读图像。
- 不要将图像作为文件读入,而是作为资源读入。
- 进行测试以确保您正在查找图片的正确位置。
- 阅读一些关于 Swing 图形的教程会让您受益匪浅,因为您所做的大部分事情看起来都像是在进行一些猜测。这些教程将向您展示正确的做事方式。您不会后悔阅读它们。
- 比在 JPanel 中绘制图像更好的方法是将它们放入 ImageIcons 并在 JLabels 中显示。
关于java - 小程序在浏览器中显示为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16887212/