方法一:直接利用JLabel的setIcon方法,可以插入图片:
public class TestImage extends JFrame {
public void launch() {
this.setTitle("TestImage");
this.setExtendedState(JFrame.MAXIMIZED_BOTH);//JFrame最大化
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//让JFrame的关闭按钮起作用
this.setVisible(true);//显示JFrame
}
public static void main(String args[]) {
TestImage testImage = new TestImage();
JPanel panel = new JPanel();
JLabel label = new JLabel();
ImageIcon img = new ImageIcon("./src/images/background.png");//创建图片对象
label.setIcon(img);
panel.add(label);
testImage.getContentPane().add(panel);
testImage.launch();
}
}
方法二:为JPanel添加背景图片的方法,要重写paintComponent这一方法:
public class ImagePanel extends JPanel {
private Image img;
public ImagePanel(Image img){
this.img = img;
Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
setSize(size);
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setLayout(null);
}
@Override
protected void paintComponent(Graphics g) {
Dimension size = this.getParent().getSize();
// g.drawImage(img, 0, 0, this);//此方法不能改变图片大小
g.drawImage(img, 0, 0, size.width, size.height, this);//此方法中的图片大小可随屏幕的改变而改变
}
public static void main(String[] args) {
JFrame frame = new JFrame("ImagePanel");
ImagePanel panel = new ImagePanel(new
ImageIcon("./src/images/background.png").getImage());
frame.getContentPane().add(panel);
frame.pack();
frame.setExtendedState( Frame.MAXIMIZED_BOTH );//最大化屏幕
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//让JFrame的关闭按钮起作用
frame.setVisible(true);//显示JFrame
}
}