Java中显示图片的方法

最近在做一个swing小项目,其中需要把存储在硬盘中的图片文件显示出来,总结了如下方法:

1.

Graphics g = getGraphics();
String name = "E:/CapabilityModel/out.gif";
Image img = Toolkit.getDefaultToolkit().getImage(name);
g.drawImage(img, 538, 408,585,305, null);
g.dispose();

这种方法是在界面上选取一定空间来显示图片,不能自动匹配图片大小,如果图片过大,则会产生图片较模糊,而且不能根据图片文件的内容更改来实时更新显示图片,示例图如下:

 

2.

JLabel imgLabel = new JLabel(new ImageIcon("D:/AGVsModel/temp/out.gif"));
setTitle("ShowImage");
JPanel cp = (JPanel) this.getContentPane();
JPanel imgPanel = new JPanel();
imgPanel.add(imgLabel);

cp.add(imgPanel, BorderLayout.CENTER);
this.setSize(950,320);
this.setVisible(true);
this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

这种方法是以弹出一个对话框来显示图片,但也不能根据图片文件的内容更改来实时显示图片,后来百度,把第一行代码改为:

JLabel imgLabel=null;
try {
imgLabel = new JLabel(new ImageIcon(ImageIO.read(new File("E:/CapabilityModel/out.gif"))));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

这样就达到了我想要的结果了,嘻嘻。。。示例图如下:

3.

protected Shell shell;
public static Display myDisplay;
public static boolean internalCall = false;

/**
* Open the window.
*/
public void open() {
Display display = Display.getDefault();
createContents(myDisplay);
Image img = new Image(display, "E:/CapabilityModel/out.gif");
shell.open();
center(display,shell);
GC gc = new GC(shell);
gc.drawImage(img, 0, 0);
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
img.dispose();
if (internalCall) display.dispose();
}

/**
* Create contents of the window.
*/
protected void createContents(Display display) {
myDisplay = display;
shell = new Shell();
shell.setSize(900, 400);
shell.setText("Show Image");
}
public static void center(Display display, Shell shell)
{
Rectangle bounds = display.getPrimaryMonitor().getBounds();
Rectangle rect = shell.getBounds();
int x = bounds.x + (bounds.width - rect.width) / 2;
int y = bounds.y + (bounds.height - rect.height) / 2;
shell.setLocation(x, y);
}

本来挺中意这种方法的,可以实时更新显示图片,但弹出框总是显示在界面的后面,而且将项目导出成jar文件运行时,居然不能显示图片,然后果断放弃了。

写代码就是不断遇到问题,然后不断解决问题,再总结转化为自己的经验,每解决一个问题就觉得好有成就感。

未经允许,不可转载!

 

 

 

 

 

 

 

 

 

posted @ 2017-02-20 15:30  金露雪莲  阅读(1232)  评论(1编辑  收藏  举报