Import java. AWT .*;
Import javax. Swing .*;
Public class imagepanel extends jpanel {
Private image IMG;
Public imagepanel (image IMG) {// construct
This. IMG = IMG;
Dimension size = new dimension (IMG. getwidth (null), IMG. getheight (null); // obtain the image size.
Setsize (size );
Setpreferredsize (size );
Setminimumsize (size );
Setmaximumsize (size );
Setlayout (null); // use the absolute layout manager.
}
Public void paintcomponent (Graphics g ){
G. drawimage (IMG, 0, 0, null );
}
}
Note: I used the paintcomponent (Graphics g) method instead of the painting (Graphics g) method. Otherwise, the child components added to this Panel cannot be drawn.
Below is a test class:
Import java. AWT .*;
Import javax. Swing .*;
Public class testpanel {
Public static void main (string [] ARGs ){
Image IMG = new imageicon ("images/bg.jpg"). getimage ();
Jframe frame = new jframe ("my hack one ");
Imagepanel Panel = new imagepanel (IMG );
Frame. getcontentpane (). Add (panel );
Frame. Pack ();
Frame. setdefaclocloseoperation (jframe. exit_on_close );
Frame. setvisible (true );
}
}