0

I am using simple JPanel to draw an image, but when I pass the normal argument such as filename itself, then it is displaying the image. But when I pass the image name from other class then it is not displaying the image. When I pass ImageIcon("D:\\25134.jpg").getimage() then the image is displayed but when i pass parameters such as ImageIcon("D:\\"+id+".JPG").getImage() then it is not displaying image.

Here is sample code

import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;

public class DrawingPanel extends JPanel {

    private int fontSize1 = 32;
    private int fontsize2=32;
    private String Fname,lname,id;
    private Image img1;
    private int messageWidth;

    public DrawingPanel(String Firstname,String lastname,String contactid) {
        Fname=Firstname;
        lname=lastname;
        id=contactid;
        System.out.println(id);

        setBackground(Color.white);
        Font font = new Font("Serif", Font.PLAIN, fontSize1);
        setFont(font);
        System.out.println(id);
        img1=new ImageIcon("D:\\"+id+".JPG").getImage();
        FontMetrics metrics = getFontMetrics(font);

        setPreferredSize(new Dimension(440, 400));
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D)g;
        int x = messageWidth/10;
        int y = fontSize1*5/2;
        g2d.translate(x, y);
        g2d.setPaint(Color.lightGray);
        AffineTransform origTransform = g2d.getTransform();
        g2d.shear(-0.95, 0);
        g2d.scale(1, 3);

        g2d.setTransform(origTransform);
        g2d.setPaint(Color.black);
        g2d.drawString(Fname,25 , 50);
        g2d.drawString(lname, 125,100);
        g2d.drawImage(img1, 280, 190, this);
    }
}
nIcE cOw
  • 24,468
  • 7
  • 50
  • 143
MandarCT
  • 57
  • 1
  • 10
  • Please have a look at, how to [add Images to the Project](http://stackoverflow.com/a/9866659/1057230) and this [related example](http://stackoverflow.com/a/15187181/1057230), more info can be found on [info](http://stackoverflow.com/tags/embedded-resource/info) page of [tag:embedded-resource] – nIcE cOw Sep 25 '13 at 12:25
  • 1
    Your code is true , so please check the image path and Try to print the output and know if there an image or not , so Try this first and tell me if there error ` Image i=null; try { i = ImageIO.read(new File("D:\\"+id+".JPG")); } catch (IOException ex) { Logger.getLogger(DrawingPanel.class.getName()).log(Level.SEVERE, null, ex); } img1 = new ImageIcon(i).getImage();` – Alya'a Gamal Sep 25 '13 at 12:39
  • this error came out Sep 25, 2013 6:20:20 PM drawing.DrawingPanel SEVERE: null – MandarCT Sep 25 '13 at 12:50

0 Answers0