2012-01-25 176 views
3

我想添加圖片到框架,但我無法理解我應該保留圖片文件的位置,我應該如何提供圖片的路徑?圖片加載路徑

我已經在My Document文件夾中放置了一個圖像,並給出了該路徑,但它給出了錯誤消息。

我有以下代碼。

import java.awt.*; 
import java.awt.image.BufferedImage; 
import java.io.*; 
import javax.imageio.ImageIO; 
import javax.swing.*; 

public class Test extends JPanel { 
    BufferedImage image; 

    public Test(BufferedImage image) { 
     this.image = image; 
    } 

    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     // Draw image centered. 
     int x = (getWidth() - image.getWidth())/2; 
     int y = (getHeight() - image.getHeight())/2; 
     g.drawImage(image, x, y, this); 
    } 

    public static void main(String[] args) throws IOException { 
     String path = "images.jpeg"; 
     BufferedImage image = ImageIO.read(new File(path)); 
     Test contentPane = new Test(image); 
     // You'll want to be sure this component is opaque 
     // since it is required for contentPanes. Some 
     // LAFs may use non-opaque components. 
     contentPane.setOpaque(true); 
     contentPane.setLayout(new GridBagLayout()); 
     GridBagConstraints gbc = new GridBagConstraints(); 
     gbc.insets = new Insets(5,5,5,5); 
     gbc.weightx = 1.0; 
     gbc.weighty = 1.0; 
     // Add components. 
     for(int j = 0; j < 8; j++) { 
      gbc.gridwidth = ((j+1)%2 == 0) ? GridBagConstraints.REMAINDER 
              : GridBagConstraints.RELATIVE; 
      contentPane.add(new JButton("button " + (j+1)), gbc); 
     } 
     JFrame f = new JFrame(); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     f.setContentPane(contentPane); 
     f.setSize(400,400); 
     f.setLocation(200,200); 
     f.setVisible(true); 
    } } 

回答

6

,我應該保持圖像文件..

因爲它似乎是一個「應用程序資源」,我說把它的運行時類路徑應用程序。這通常可以通過將它添加到一個Jar中的目錄(例如images)來實現。

..以及如何給圖像的路徑?

通過從所獲得的URL訪問它:

URL urlToImage = this.getClass().getResource("/images/the.png"); 

ImageIO.read()還可以接受URL或更通用,InputStream

9

有幾個地方爲您的形象。

  • 相對路徑,在您的示例應用程序開始查找在文件夾中的圖像有你啓動它(請檢查有沒有應用程序啓動)。您可以通過"resources\\images.jpeg"

  • 絕對路徑圖像和訪問創建文件夾「資源」,像"C:\\Documents and settings\\<username>\\My Documents\\images.jpeg"

  • 類路徑 - 把圖像在同一文件夾/包有您的測試類放置。這個資源可以打包成.jar文件。

    BufferedImage image = ImageIO.read(Test.class.getResourceAsStream("images.jpeg"));

  • 任何有效的URL,你的榜樣

    BufferedImage image = ImageIO.read(URI.create("http://www.gravatar.com/avatar/d5f91983a9d9cfb69981b6108a63b412?s=32&d=identicon&r=PG").toURL());

的頭像