实现此目的的一种方法是重写paintComponent每次JPanel刷新时绘制背景图像的方法。
例如,可以将子类化JPanel,并添加一个字段以保存背景图片,然后覆盖该paintComponent方法:
public class JPanelWithBackground extends JPanel {
private Image backgroundImage;
// Some code to initialize the background image.
// Here, we use the constructor to load the image. This
// can vary depending on the use case of the panel.
public JPanelWithBackground(String fileName) throws IOException {
backgroundImage = ImageIO.read(new File(fileName));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw the background image.
g.drawImage(backgroundImage, 0, 0, this);
}
}
(以上代码尚未经过测试。)
以下代码可用于将添加JPanelWithBackground
到中JFrame
:
JFrame f = new JFrame();
f.getContentPane().add(new JPanelWithBackground("sample.jpeg"));