java添加背景图片代码
时间: 2023-07-02 16:20:08 浏览: 83
以下是在Java Swing中添加背景图片的代码示例:
```
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class BackgroundImage extends JPanel {
private Image backgroundImage;
public BackgroundImage(String fileName) throws IOException {
backgroundImage = ImageIO.read(new File(fileName));
}
@Override
public Dimension getPreferredSize() {
return new Dimension(backgroundImage.getWidth(null), backgroundImage.getHeight(null));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(backgroundImage, 0, 0, null);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Background Image Example");
try {
frame.setContentPane(new BackgroundImage("background.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
```
请注意,上面的示例假设你已经有了一张名为 "background.jpg" 的图片文件,并将其放在了与Java文件相同的目录下。如果你有不同的文件名或路径,请相应地更改 `BackgroundImage` 构造函数中的参数。
阅读全文