Java 带有图像背景的 JPanel
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4051408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JPanel with image background
提问by Jessy
How to put image background on JPANEL?
如何在 JPANEL 上放置图像背景?
JPanel pDraw = new JPanel(new GridLayout(ROWS,COLS,2,2));
pDraw.setPreferredSize(new Dimension(600,600)); //size of the JPanel
pDraw.setBackground(Color.RED); //How can I change the background from red color to image?
回答by Reese Moore
It is probably easiest to load the Imageinto an ImageIconand display it in a JLabel, however:
To directly 'draw' the image to the JPanel, override the JPanel's paintComponent(Graphics)method to something like the following:
将 加载Image到 an 中ImageIcon并在 a 中显示它可能是最简单的JLabel:
要直接将图像“绘制”到 JPanel,请将 JPanel 的paintComponent(Graphics)方法覆盖为如下所示:
public void paintComponent(Graphics page)
{
super.paintComponent(page);
page.drawImage(img, 0, 0, null);
}
where imgis an Image(possibly loaded through the ImageIO.read()call).
其中img是Image(可能通过加载ImageIO.read()呼叫)。
Graphics#drawImageis a heavily overloaded command which will allow you to be highly specific in how, how much, and where you paint the image to the component.
Graphics#drawImage是一个重载的命令,它将允许您在如何、多少以及将图像绘制到组件的位置上非常具体。
You can also get 'fancy' and scale the image to your pleasing using the Image#getScaledInstancemethod. This will take a -1for either the widthor the heightparameter in order to keep the aspect ratio of the image the same.
您还可以使用该Image#getScaledInstance方法获得“花哨”并将图像缩放到您满意的程度。为了保持图像的纵横比相同,这将为-1thewidth或 theheight参数取 a 。
Putting it in a more fancy way:
把它放在一个更花哨的方式:
public void paintComponent(Graphics page)
{
super.paintComponent(page);
int h = img.getHeight(null);
int w = img.getWidth(null);
// Scale Horizontally:
if ( w > this.getWidth() )
{
img = img.getScaledInstance( getWidth(), -1, Image.SCALE_DEFAULT );
h = img.getHeight(null);
}
// Scale Vertically:
if ( h > this.getHeight() )
{
img = img.getScaledInstance( -1, getHeight(), Image.SCALE_DEFAULT );
}
// Center Images
int x = (getWidth() - img.getWidth(null)) / 2;
int y = (getHeight() - img.getHeight(null)) / 2;
// Draw it
page.drawImage( img, x, y, null );
}

