java 中怎样给一个窗口加一个背景图片?

来源:百度知道 编辑:UC知道 时间:2024/05/16 00:45:22
最好是详细的解释,
有好的话, 还会加分。

一楼说得对,我给你代码吧,你写个窗口把这个JPanel放进去就行:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
public class PicPanel extends JPanel
{
BufferedImage img;
public PicPanel(String path)
{
super();
try
{
img = ImageIO.read(new File(path));
}
catch (Exception e)
{
System.out.println("Error: "+e.toString());
}
}
public void paintComponent(Graphics g)//绘制图片的方法
{
try
{
Rectangle rect = new Rectangle(0,0,img.getWidth(null),img.getHeight(null));
TexturePaint texture = new TexturePaint(img,rect);
Graphics2D g2 = (Graphics2D)g;
g2.setPaint(texture);
g2.fillRect(0,0,this.getWidth(),this.getHeight());
super.paintComponent(g);
}
catch(Exception e)
{
System.out.println("Error: "+e.toString());
}<