First, import the relevant packages:
Import Java.awt.BorderLayout;
Import Java.awt.Container;
Import Javax.swing.ImageIcon;
Import Javax.swing.JFrame;
Import Javax.swing.JLabel;
Import Javax.swing.JPanel;
You can also use:
Import java.awt.*;
Import javax.swing.*;
Next, create a Java form object and set it to visible
Eg:jfram frame = JFrame ();//Create a form
Frame.setvisible (TRUE);//Set form visible, invisible by default
Finally, write the following code:
/*
* The following 7 lines add a background picture to the form
*/
ImageIcon img = new ImageIcon ("e:\\1" + ". gif");//This is a background image
JLabel Imglabel = new JLabel (IMG);//Place the background map in the label.
Frame.getlayeredpane (). Add (Imglabel, New Integer (Integer.min_value));//Note This is the key, add the background tag to the Jfram layeredpane panel.
Imglabel.setbounds (0,0,img.geticonwidth (), Img.geticonheight ());//Set the position of the background label
Container Cp=frame.getcontentpane ();
Cp.setlayout (New BorderLayout ());
((JPanel) CP). Setopaque (false); Notice here that the content panel is set to transparent. This allows the background in the Layeredpane panel to be displayed.
Write a try now!!!
The complete code is as follows:
Package the eighth chapter;
Import Java.awt.BorderLayout;
Import Java.awt.Container;
Import Javax.swing.ImageIcon;
Import Javax.swing.JFrame;
Import Javax.swing.JLabel;
Import Javax.swing.JPanel;
public class Myfirstframe extends JFrame {
/**
* Listen to the Valley ~
* Version 1.0
*/private static final long serialversionuid = 1L;
public static void Main (string[] args) {
TODO auto-generated Method Stub
Myfirstframe frame=new myfirstframe ();
Frame.setvisible (TRUE);//Set form visible, invisible by default
/*
* The following 7 lines add a background picture to the form
*/
ImageIcon img = new ImageIcon ("E:\\1.gif");//This is a background image
JLabel Imglabel = new JLabel (IMG);//Place the background map in the label.
Frame.getlayeredpane (). Add (Imglabel, New Integer (Integer.min_value));//Note This is the key, add the background tag to the Jfram layeredpane panel. Imglabel.setbounds (0,0,img.geticonwidth (), Img.geticonheight ());//Set the position of the background label
Container Cp=frame.getcontentpane ();
Cp.setlayout (New BorderLayout ());
((JPanel) CP). Setopaque (false); Notice here that the content panel is set to transparent. This allows the background in the Layeredpane panel to be displayed.
}
Public Myfirstframe () {
Super (); Inherits the parent class construction method Settitle ("form created with the JFrame class");
SetBounds (100,100,315,320); Set the form display position and size
System.out.println (Getforeground ());
Getcontentpane (). setlayout (null);//set to not take any layout manager
Setdefaultcloseoperation (Jframe.exit_on_close); }
}
How to add a background image to Java