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?
这是一个解释。
将Image
加载到ImageIcon
并将其显示在JLabel
可能最简单,但是:
要直接“绘制”图像到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
方法获得“花哨”并将图像缩放到令人愉悦的Image#getScaledInstance
。 对于width
或height
参数,这将采用-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 ); }