如果从不同的类传递文件名,则无法在JPanel上显示图像

时间:2013-09-25 12:16:20

标签: java image io jpanel

我使用简单的JPanel来绘制图像,但是当我传递正常参数(例如 filename 本身)时,它就会显示图像。但是,当我从其他类传递图像名称时,它不显示图像。当我通过ImageIcon("D:\\25134.jpg").getimage()时 然后显示图像,但是当我传递ImageIcon("D:\\"+id+".JPG").getImage()等参数时,它不会显示图像。

以下是示例代码

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);
    }
}

0 个答案:

没有答案