How to set an image as the background of a frame in the swing GUI of Java?

I have created a GUI using swing in Java I must now send a sample The JPEG image is placed as a background on the frame where I place my component How?

Solution

There is no concept of "background image" in JPanel, so we must implement this function in our own way

One way to do this is to override the paintcomponent method that draws the background image each time the JPanel is refreshed

For example, subclass to JPanel, add a field to save the background image, and override the paintcomponent method:

public class JPanelWithBackground extends JPanel {

  private Image backgroundImage;

  // Some code to initialize the background image.
  // Here,we use the constructor to load the image. This
  // can vary depending on the use case of the panel.
  public JPanelWithBackground(String fileName) throws IOException {
    backgroundImage = ImageIO.read(new File(fileName));
  }

  public void paintComponent(Graphics g) {
    super.paintComponent(g);

    // Draw the background image.
    g.drawImage(backgroundImage,this);
  }
}

(the above code has not been tested.)

You can add jpanelwithbackground to the JFrame using the following code:

JFrame f = new JFrame();
f.getContentPane().add(new JPanelWithBackground("sample.jpeg"));

In this case, imageio The read (file) method is used to read external JPEG files

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>