我想在一个面板里加个.jpg格式的背景图片.该怎么做啊.
写一个继承自JPanel的面板,然后重写里面的
paintComponent方法,在里面画图就行了
import java.awt.*;
import javax.swing.*;
import java.net.*;
public class ImageBackground extends JPanel{
URL url=null;
Image image=null;
public ImageBackground(){
url=this.getClass().getResource("Sunset.jpg");
Toolkit toolkit=Toolkit.getDefaultToolkit();
image=toolkit.getImage(url);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(image,0,0,this);
}
public static void main(String[] args){
JFrame frame=new JFrame();
frame.setTitle("显示图形");
frame.setSize(640,480);
frame.getContentPane().add(new ImageBackground());
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}