Java Code
import java.awt.*;
import javax.swing.*;
public class ImgBackground extends JApplet
{
JLabel myplay, name;
Image img;
ImgPanel ipanel;
public void init( )
{
myplay = new JLabel( "My Fun Playground" );
name = new JLabel( "Java Rules" );
myplay.setForeground( Color.YELLOW );
name.setForeground( Color.RED );
img = getImage( getCodeBase( ), "houseLake.png" );
ipanel = new ImgPanel( img );
myplay.setFont( new Font( "Serif", Font.BOLD, 20 ) );
ipanel.setLayout( new GridLayout( 2,1 ) );
ipanel.add( myplay );
ipanel.add( name );
add( ipanel );
}
}
import java.awt.*;
import javax.swing.*;
public class ImgPanel extends JPanel
{
Image img;
public ImgPanel( Image ic )
{
img=ic;
}
public void paintComponent( Graphics g )
{
super.paintComponent(g);
if ( img != null )
{
int imgWidth = img.getWidth(this); // find the width of the image
int panelWidth = this.getWidth( ); // find the width of the panel
int x = (panelWidth - imgWidth ) / 2; // calculate x to center the img
int imgHeight = img.getHeight( this ); // find height of image
int panelHeight = this.getHeight( ); // find height of panel
int y = (panelHeight - imgHeight ) / 2; // calculate y to center the img
g.drawImage(img,x,y,img.getWidth(this),img.getHeight(this),this); // paint the image
}
}
}
©2007 by E.S.Boese. All Rights Reserved