2010-06-28 74 views
1

嘿,那裏,我只是試圖把一個與JFileChooser在一個標籤上拍攝的圖像;但它沒有按照我想要的方式工作。這是我試過的代碼;如何將帶有JFileChooser的圖像圖標放在標籤上?

import java.io.*; 
import javax.swing.*; 
import java.util.*; 


public class Main { 

    public static void main(String[] args) { 


     JFileChooser chooser = new JFileChooser(); 

     JFrame frame = new JFrame("My Frame"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     JPanel panel = new JPanel(); 

     chooser.showOpenDialog(null); 

     File file = chooser.getSelectedFile(); 
     ImageIcon icon = new ImageIcon(file.getName()); 
     JLabel label = new JLabel(icon); 

//  JLabel label2 = new JLabel("try try catch it"); 

     panel.add(label); 
//  panel.add(label2); 


     frame.getContentPane().add(panel); 
     frame.pack(); 
     frame.setVisible(true); 


    } 

} 

有什麼建議嗎?

+0

謝謝大家,當我使用getPath()方法時,它確實有效! – makyol 2010-06-28 21:55:15

回答

1

關閉。

您會注意到,當您查看file.getName()時,您會看到它會爲您提供所選文件的名稱。您正在尋找路徑而不是文件的名稱。

查看您是否可以在API中尋找File以瞭解如何獲取路徑。

1

您應該使用file.getPath()而不是file.getName()。你也應該在美國東部時間做你的繪畫作品。

相關問題