To create Image Panel in Swing


In this article you can get idea how to use a image panel in Swing Application.By using this code you can make your swing application much transparent image view.

// Comment
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Main;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
 
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
 *
 * @author allinalljava.blogspot.com
 */
public class ImagePanel  extends JPanel{
     
 
  private Image img;
 
  public ImagePanel(String img) {
    this(new ImageIcon(img).getImage());
  }
 
  public ImagePanel(Image img) {
    this.img = img;
    Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
    setPreferredSize(size);
    setMinimumSize(size);
    setMaximumSize(size);
    setSize(size);
    setLayout(null);
  }
 
  public void paintComponent(Graphics g) {
    g.drawImage(img, 0, 0, null);
  
}

}



In the above code you can easily create a Image panel.But In order to implement the application You can following code.By means of that You can enjoy Better Output Look and Feel in application.
// Comment

JPanel mainpanel = new ImagePanel(new ImageIcon(this.getClass().getResource("/images/12.jpg")).getImage());

Following Program describes sample implementation of Image Panel in Swing
// Comment
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Main;

/**
 *
 * @author j
 */

    import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
 
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
 
public class NewClass {
 
  public static void main(String[] args) {
    ImagePanel panel = new ImagePanel(new ImageIcon("C:\\12.jpg").getImage());
 
    JFrame frame = new JFrame();
    frame.getContentPane().add(panel);
    frame.pack();
    frame.setVisible(true);
  }
}
 
OutPut Window

raja P Web Developer

5 comments:

Related Posts Plugin for WordPress, Blogger...