Tuesday, 30 September 2014

Java Swings : JPanel : JPanel with Image Background



                                                    Working with Jpanels

 JPanels with Image Background
Using Jpanels to add components are common , we set layout and add components according to our need but what if we want to add Background Image without changing actual behaviors of JPanel.
So this section will help you to create such a JPanel


This is the first Class JPanelExample which is a JFrame. With JPanel and JButton added to it , only difference is JPanel is the customized JPanel.
Background image path is passed as an argument to construct of this new JPanel Class.
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class JPanelExample extends JFrame {
           
            public JPanelExample() {
                        this.setTitle("JPanel Example");
                        this.setBounds(600, 200, 300, 300);
                        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        ImageIcon titleIcon = new ImageIcon("images/titleIcon.png");
                        this.setIconImage(titleIcon.getImage());
                        JPanel pnlOuter = new PnlImage("images/background.png");
                        pnlOuter.setBackground(Color.GRAY);
                        this.setLayout(new BorderLayout());

                        JButton btnTest = new JButton("button above image panel");
                        btnTest.setBounds(140, 20, 220, 40);
                        pnlOuter.add(btnTest);

                        this.add(pnlOuter, BorderLayout.CENTER);

            }

            public static void main(String[] args) {
                        JPanelExample testFrame = new JPanelExample();
                        testFrame.setVisible(true);

            }

}




This Class below is the customized JPanel which draws images to the background of JPanel. In this class has over ridden the paint method of JPanel and used g.drawImage(img,0,0,null) method to draw image in JPanel.
So by adding below class in your project . Image panel can be used by calling same as shown in above example.
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JPanel;

public class PnlImage extends JPanel
{
            private Image img;
   
    public PnlImage(String imageFile) {
            this(new ImageIcon(imageFile).getImage());
    }
       
    public PnlImage(Image image) {
            this.img=image;
            Dimension size=new Dimension(img.getWidth(null), img.getHeight(null));
            this.setPreferredSize(size);
            setLayout(null);
    }
    
    public void paintComponent(Graphics g) {
    g.drawImage(img,0,0,null);
    }   
}




1 comment: