首先在JFrame中添加一个JPanel,重写JPanel方法
package com.project.swing;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class BackgroundJPanel extends JPanel{
Image img;
// BackgroundJPanel backPanel;
public BackgroundJPanel(Image img){
this.img=img;
this.setOpaque(true);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(img,0,0,this.getWidth(),this.getHeight(),this);
}
}
我在测试类test.class添加代码
BackgroundJPanel backgroundJPanel=new BackgroundJPanel(new ImageIcon(test.class.getResource("first.jpg")).getImage());//这里的test是测试类名,first.jpg
//自行添加到test.class所在的包内
backgroundJPanel.setBounds(0,0,1000,618);//设置JPanel的位置以及height与Width;
最后添加到JFrame中
this.add(backgroundJPanel);