我试图在 JFrame 中显示背景图像,但图像没有显示,而且我找不到代码中的错误是什么。
public class GraphicsComponent extends JComponent
{
int xPosition = 200;//initializes and declares the x coordinate
int yPosition = 400;//initializes and declares the y coordinate
Image i;
public GraphicsComponent()
{
try{
File sky = new File("lib/background.png");
i = ImageIO.read(sky);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void paintComponent(Graphics g) //overrides paintComponent method in JComponent
{
if (i == null) return;
g.drawImage(i, 0, 0, this);
}
最佳答案
为什么要创建自定义组件?如果您创建自定义组件,那么您还需要重写组件的 getPreferredSize()
方法以返回图像的大小,以便布局管理器能够以正确的大小绘制组件。
所以组件的大小可能为零,因此没有什么可绘制的。
最简单的解决方案是仅使用 JLabel
和 ImageIcon
并让布局管理器处理大小问题。
关于java - 在 Java 中显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23837704/