This guide is made to add an image as a Background to JFrame.
So, to achive it, we will modify the ContentPane of the JFrame, by using the JFrame's
setContentPane()
method. We will also require an additional class which will be our ContentPane of out JFrame. This new class will extend JPanel class.i.e Image -> JPanel -> ContentPane of JFrame = Background Image on JFrame
Here we go,
- In the constructor of the Main class, we will set the
contentPane()
and also pass the path of our image file as String.
public Main() { setContentPane(new BgPanel("image.jpg")); // setting new ContentPane setVisible(true); // display the JFrame setSize(500,300); // set Size of the JFrame }
read()
, it accepts a File object and returns a BufferedImage as a result. img = ImageIO.read(new File(path));
IOException
has to be handled for the read()
method.
IllegalArgumentException
can also be thrown by read()
method if the input is null.But our input won't be null as we are passing the image path as parameter. But
IOException
has to be handled.BgPanel(String path) { try { img = ImageIO.read(new File(path)); } catch(IOException e) { e.printStackTrace(); } }
paintComponent(Graphics g)
method. A call to the super class is made to clear the background of the component and the drawImage()
method is used to draw an image on the JPanel.
@Override protected void paintComponent(Graphics g) { super.paintComponent(g); if(img != null) { g.drawImage(img,0,0,this.getWidth(),this.getHeight(),this); } }
Here is the final code:
/* * Author: Ashish Gundewad. */
import java.io.*; import java.awt.*; import javax.swing.*; import javax.imageio.*; public class Main extends JFrame { public Main() { setContentPane(new BgPanel("image.jpg")); setVisible(true); setSize(500,300); } public static void main(String [] args) { new Main(); } } class BgPanel extends JPanel { private Image img; BgPanel(String path) { try { img = ImageIO.read(new File(path)); } catch(IOException e) { e.printStackTrace(); } } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if(img != null) { g.drawImage(img,0,0,this.getWidth(),this.getHeight(),this); } } }
No comments:
Post a Comment