Java中顯示圖片的方法,Java顯示圖片方法

來源:互聯網
上載者:User

Java中顯示圖片的方法,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檔案運行時,居然不能顯示圖片,然後果斷放棄了。

寫代碼就是不斷遇到問題,然後不斷解決問題,再總結轉化為自己的經驗,每解決一個問題就覺得好有成就感。

 

 

 

 

 

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.