Java 带图像背景的JPanel
如何在JPANEL上放置图像背景Java 带图像背景的JPanel,java,jpanel,background-image,Java,Jpanel,Background Image,如何在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? 解释。将图像加载到图像图标
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?
解释。将
图像
加载到图像图标
并在标签
中显示可能是最简单的方法,但是:要直接将图像“绘制”到JPanel,请将JPanel的
paintComponent(Graphics)
方法重写为以下内容:
public void paintComponent(Graphics page)
{
super.paintComponent(page);
page.drawImage(img, 0, 0, null);
}
其中,img
是一个Image
(可能通过ImageIO.read()
调用加载)
Graphics#drawImage
是一个超负荷的命令,它允许您非常具体地说明将图像绘制到组件的方式、数量和位置
您还可以使用image#getScaledInstance
方法获得“新奇”并将图像缩放到您喜欢的程度。这将为宽度
或高度
参数采用-1
,以保持图像的纵横比相同
用一种更为奇特的方式:
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 );
}
我会用一个。应该尽你所能,