如何给一个jpanel添加背景
how to add a background to a jpanel
我想将 jlabel 添加到 jpanel 我已经使用了这段代码
JLabel background=new JLabel(new ImageIcon("Myimage.jpg"));
panel.add(background);
frame.setContentPane(panel);
图像的大小是最小化的 window 而不是最大化的,所以当我最大化 window 时它显示一个空的 space,这是我不想要的。我想要我添加的 jpanel 的背景
只需重写 JPanel 的 paintComponent(Graphics g) : void
。以下解决方案会将您的图像始终缩放到面板尺寸。
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JPanel;
public class ImagePanel extends JPanel {
private Image image;
public void setBackgroundImage(Image image) {
this.image = image;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(this.image, 0, 0, this.getWidth(), this.getHeight(), this);
}
}
对于性能和质量方面,设置一些 RenderingHints.For more information see Controlling Rendering Quality。
也可能很有用
请考虑先搜索再提问。也许这个答案也解决了您的问题 How to fit Image size to JFrame Size??
我想将 jlabel 添加到 jpanel 我已经使用了这段代码
JLabel background=new JLabel(new ImageIcon("Myimage.jpg"));
panel.add(background);
frame.setContentPane(panel);
图像的大小是最小化的 window 而不是最大化的,所以当我最大化 window 时它显示一个空的 space,这是我不想要的。我想要我添加的 jpanel 的背景
只需重写 JPanel 的 paintComponent(Graphics g) : void
。以下解决方案会将您的图像始终缩放到面板尺寸。
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JPanel;
public class ImagePanel extends JPanel {
private Image image;
public void setBackgroundImage(Image image) {
this.image = image;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(this.image, 0, 0, this.getWidth(), this.getHeight(), this);
}
}
对于性能和质量方面,设置一些 RenderingHints.For more information see Controlling Rendering Quality。
也可能很有用请考虑先搜索再提问。也许这个答案也解决了您的问题 How to fit Image size to JFrame Size??