gpt4 book ai didi

java - 背景图像未显示在 JPanel 中

转载 作者:行者123 更新时间:2023-11-30 06:43:08 25 4
gpt4 key购买 nike

我正在尝试在另一个 JPanel 中创建一个带有背景图像的 JPanel,但背景图像未显示。我该如何解决这个问题?

public class CustomPanel extends JPanel{
Image img;
private final static String BACKGROUND = "images/background.png";

private void loadImage(String filename){
try{
img = Toolkit.getDefaultToolkit().getImage(filename);
} catch(Exception e){}
}

@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(this.img, 0, 0,null);//display this image as a background
Toolkit.getDefaultToolkit().sync();//makes animations smooth
}

public CustomPanel(){
this.setLayout(null);
this.loadImage(this.BACKGROUND);//prepare background image
this.repaint();//set bg image


}

}

这是 MainPanel,它将容纳其他带有背景的 JPanel。

public class MainPanel extends JPanel{
public Container container;
public MainPanel(Container container){
this.setLayout(null);
this.container = container;
CustomPanel panel= new CustomPanel();
this.add(panel);
}
}

我读过与此相关的其他问题,其中大部分是未能设置 super.paintComponent(g)。我已经在我的代码中做到了这一点,所以我真的不知道问题是什么

最佳答案

默认情况下,组件的大小为 (0, 0),因此无需绘制任何内容。

您需要重写 CustomPanelgetPreferredSize() 方法以返回图像的大小。

然后布局管理器可以使用此信息来设置面板的大小和位置。

但是,由于您只是按照实际大小绘制图像,因此另一个解决方案是将 ImageIcon 添加到 JLabel 并将标签添加到面板。仅当您计划更改图像时才需要自定义绘画,可以通过缩放图像以适应面板变化的大小。

参见Background Panel了解更多信息和示例。

关于java - 背景图像未显示在 JPanel 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44071144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com