Adding background image to JFrame
Adding background image to a JFrame is simple with the availability of ImageIO class.
Two steps are essential in drawing an image to the JFrame.
1.First we need to create an object of Image class that refers to the image,which we would like to draw on our JFrame.
2.Next we need to add the code for drawing the image in the paintComponent()method of the JComponent class,
Since we would like to draw an image,drawImage(Image img,int x,int y, Image Observer obj) method of the Graphics class would be enough.
img - it represents the Image object which refers to the actual image.
x and y- denotes the distance from the left and top of the JFrame respectively.
obj- It is an object of ImageObserver which is used to keep track of the rendering process and we need not worry about it as we can simply set it to null.
Here i have included a sample program that adds an background image to the frame.
Program:
Firstframe.java
import javax.swing.*;
import java.util.*;
import java.awt.*;
class Firstframe extends JFrame
{
Firstframe()
{
setTitle("My FirstFrame");
setSize(200,200);
setLocationByPlatform(true);
Addimage im=new Addimage("car1.gif");
add(im);
}
}
import java.util.*;
import java.awt.*;
class Firstframe extends JFrame
{
Firstframe()
{
setTitle("My FirstFrame");
setSize(200,200);
setLocationByPlatform(true);
Addimage im=new Addimage("car1.gif");
add(im);
}
}
Myframe.java
import javax.swing.*;
import java.util.*;
class Myframe
{
public static void main(String args[])
{
Firstframe f1=new Firstframe();
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setVisible(true);
}
}
import java.util.*;
class Myframe
{
public static void main(String args[])
{
Firstframe f1=new Firstframe();
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setVisible(true);
}
}
Addimage.java
import javax.swing.*;
import java.util.*;
import java.awt.*;
import javax.imageio.*;
import java.io.*;
class Addimage extends JComponent
{
public Addimage(String imgfile)
{
try
{
img=ImageIO.read(new File(imgfile));
}
catch(IOException e)
{
e.printStackTrace();
}
}
public void paintComponent(Graphics g)
{
g.drawImage(img,0,0,null);
}
private Image img=null;
}
import java.util.*;
import java.awt.*;
import javax.imageio.*;
import java.io.*;
class Addimage extends JComponent
{
public Addimage(String imgfile)
{
try
{
img=ImageIO.read(new File(imgfile));
}
catch(IOException e)
{
e.printStackTrace();
}
}
public void paintComponent(Graphics g)
{
g.drawImage(img,0,0,null);
}
private Image img=null;
}
Output:
Things to be remembered:
If you want to draw any component to a frame then you are supposed to use the paintComponent(Graphics g) method.
You need not invoke this method as it will be automatically invoked when the frame is made visible or resized.
Inside this method you have to add your drawing code.
0 comments:
Post a Comment