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?
How to put image background on 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将
Image
加载到ImageIcon
中并将其显示在JLabel
中可能是最简单的方法,但是:要将图像直接“绘制”到 JPanel,请重写 JPanel 的
paintComponent(Graphics)
方法,如下所示:其中
img
是Image
> (可能通过 ImageIO.read() 调用加载)。Graphics#drawImage 是一个重载的命令,它允许您高度具体地指定如何、多少以及在何处将图像绘制到组件。
您还可以使用
Image#getScaledInstance
方法来获得“奇特”的效果并将图像缩放到您满意的程度。这将为width
或height
参数取-1
,以保持图像的纵横比相同。用更奇特的方式来说:
It is probably easiest to load the
Image
into anImageIcon
and display it in aJLabel
, however:To directly 'draw' the image to the JPanel, override the JPanel's
paintComponent(Graphics)
method to something like the following:where
img
is anImage
(possibly loaded through theImageIO.read()
call).Graphics#drawImage
is 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.You can also get 'fancy' and scale the image to your pleasing using the
Image#getScaledInstance
method. This will take a-1
for either thewidth
or theheight
parameter in order to keep the aspect ratio of the image the same.Putting it in a more fancy way:
这里有一个解释。
Here's an explanation.