最简单的方法来设置图像作为背景的JPanel [英] Simplest way to set image as JPanel background
问题描述
如何将我的backgroung图像添加到我的JPanel,而无需创建一个新的类或方法,而是简单地通过与JPanel的属性的其余一起插入呢?
我想使用的图像,但是,我觉得每一个例子似乎暗示扩大与自己的类面板设置一个JPanel的背景。
我一直在寻找一种方式来简单地添加图像,而无需创建一个全新的类和同样的方法中(试图让一切井井有条,简单)。
下面是设置我的JPanel方法的一个例子:
公共静态的JPanel drawGamePanel(){
//创建游戏面板和属性
的JPanel的GamePanel =新JPanel();
图片背景= Toolkit.getDefaultToolkit()的createImage(Background.png);
gamePanel.drawImage(背景,0,0,NULL);
//设置返回
返回的GamePanel;
}
我试图用图像来设置一个JPanel的背景,但是,我觉得每一个例子似乎暗示扩大与它自己的类面板
块引用>是的,你将不得不延长
的JPanel
并重写的paintComponent(图形G)
函数这样做。@覆盖
保护无效paintComponent(图形G){ super.paintComponent方法(G);
g.drawImage(bgImage,0,0,NULL);
}
我一直在寻找一种方式来简单地添加图像,而无需创建一个全新的类和同样的方法内( 试图保持有组织,有简单的事情的)。
块引用>您可以使用其他组件,它允许添加图像作为图标直接例如
的JLabel
如果你想。ImageIcon的图标=新的ImageIcon(imgUrl的);
拇指的JLabel =新的JLabel();
thumb.setIcon(图标);但同样在支架上的的试图保持有组织,有简单的事情的!是什么让你觉得刚刚创建一个新的类将带你到一个混乱的世界呢?
How would I add the backgroung image to my JPanel without creating a new class or method, but simply by inserting it along with the rest of the JPanel's attributes?
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.
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).
Here is an example of the method that sets my 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
yes you will have to extend
JPanel
and override thepaintcomponent(Graphics g)
function to do so.@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).
You can use other component which allows to add image as icon directly e.g.
JLabel
if you want.ImageIcon icon = new ImageIcon(imgURL); JLabel thumb = new JLabel(); thumb.setIcon(icon);
But again in the bracket trying to keep things organized and simple !! what makes you to think that just creating a new class will lead you to a messy world ?
这篇关于最简单的方法来设置图像作为背景的JPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!