最近在做一個swing小項目,其中需要把存儲在硬碟中的圖片文件顯示出來,總結瞭如下方法: 1. Graphics g = getGraphics();String name = "E:/CapabilityModel/out.gif";Image img = Toolkit.getDefaultTo ...
最近在做一個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文件運行時,居然不能顯示圖片,然後果斷放棄了。
寫代碼就是不斷遇到問題,然後不斷解決問題,再總結轉化為自己的經驗,每解決一個問題就覺得好有成就感。