This Jpanel can dynamically load an image as a background
Copy the code code as follows:
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JPanel;
/**
* A Jpanel that can dynamically load an image as a background
*/
public class ImagePanel extends JPanel{
Image im;
//The constructor determines the size of Jpanel
public ImagePanel(Image im) {
this.im = im;
//I hope the size of the Panel can be adaptive
int width = Toolkit.getDefaultToolkit().getScreenSize().width;
int height = Toolkit.getDefaultToolkit().getScreenSize().height;
this.setSize(width,height);
}
//Draw the background
@Override
protected void paintComponent(Graphics g) {
// clear screen
super.paintComponent(g);
g.drawImage(im, 0, 0, this.getWidth(), this.getHeight(), this);
}
}
Another example of setting a background image in a JPanel panel
Copy the code code as follows:
import java.awt.*;
import javax.swing.*;
public class Demo extends JFrame
{
publicDemo()
{
super("Title");
NewPanel p = new NewPanel();
this.getContentPane().add(p); //Add the panel to the JFrame
this.setSize(596,298); //Initial window size
this.setLocationRelativeTo(null); //Set the window to be centered
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args)
{
new Demo();
}
class NewPanel extends JPanel
{
public NewPanel()
{
}
public void paintComponent(Graphics g)
{
int x=0,y=0;
java.net.URL imgURL=getClass().getResource("test.jpg");
//test.jpg is a test image, placed in the same directory as Demo.java
ImageIcon icon=new ImageIcon(imgURL);
g.drawImage(icon.getImage(),x,y,getSize().width,getSize().height,this);
while(true)
{
g.drawImage(icon.getImage(),x,y,this);
if(x>getSize().width && y>getSize().height)break;
//This code is to ensure that when the window is larger than the picture, the picture can still cover the entire window.
if(x>getSize().width)
{
x=0;
y+=icon.getIconHeight();
}
else
x+=icon.getIconWidth();
}
}
}
}