如何在不创建新类或方法的情况下将背景图像添加到我的 JPanel,而只需将它与 JPanel 的其余属性一起插入?
我正在尝试使用图像设置 JPanel 的背景,但是,我发现的每个示例似乎都建议使用自己的类扩展面板。
我一直在寻找一种方法来简单地添加图像,而无需创建一个全新的类,并且使用相同的方法(试图使事情井井有条和简单)。
这是设置我的 JPanel 的方法示例:
public static JPanel drawGamePanel(){
//Create game panel and attributes
JPanel gamePanel = new JPanel();
Image background = Toolkit.getDefaultToolkit().createImage("Background.png");
gamePanel.drawImage(background, 0, 0, null);
//Set Return
return gamePanel;
}
最佳答案
I am trying to set a JPanel's background using an image, however, every example I find seems to suggest extending the panel with its own class
是的,您必须扩展 JPanel
并覆盖 paintcomponent(Graphics g)
函数才能这样做。
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bgImage, 0, 0, null);
}
I have been looking for a way to simply add the image without creating a whole new class and within the same method (trying to keep things organized and simple).
您可以使用其他允许直接将图像添加为图标的组件,例如JLabel
如果需要的话。
ImageIcon icon = new ImageIcon(imgURL);
JLabel thumb = new JLabel();
thumb.setIcon(icon);
但又在括号中试图让事情井然有序!!是什么让您认为仅仅创建一个新类就会把您带到一个困惑的世界?
关于java - 将图像设置为 JPanel 背景的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19125707/