2015-05-26 37 views
0

如何創建我需要附加到個人圖像的個人細節?當點擊按鈕時,它可以選擇圖片,但我仍然無法弄清楚如何設置這種編碼,任何人都可以幫助解決這個問題?netbeans:使用Jbutton在Jlabel中附加圖像

JFileChooser chooser=new JFileChooser(); 
chooser.showOpenDialog(null); 
File f=chooser.getSelectedFile(); 

personal_image. 
+0

爲了更好地幫助越早,張貼[MCVE](http://stackoverflow.com/help/ (最小完整可驗證示例)或[SSCCE](http://www.sscce.org/)(簡短的,獨立的,正確的示例)。 –

回答

1

正如我注意到,你在使用NetBeans IDE,NetBeans的已經提供了便利寫的actionPerformed爲一個JButton在ActionEvent的情況。

我建議你寫在你的JButton的actionPerformed下面的代碼與動作事件EVT如下所述: -

private void DesiredButtonActionPerformed(java.awt.event.ActionEvent evt){ 

// Add your mentioned code here before coding this. 
try{ 
Image image = ImageIO.read(f); 
ImageIcon icon = new ImageIcon(image); 
// JLabel toBeSet = new JLabel(); 
// considering that you have a JLabel having name as what I've used here 
toBeSet.setIcon(icon); 
} 
catch(IOException ioe){ 
System.out.println("Exception occured while setting Image on the Label!"); 
} 

} 
+0

1)由於新創建的標籤永遠不會添加到任何內容,因此寫入的代碼不會有明顯的影響。此外,在GUI顯示後向GUI添加組件需要特別注意。 2)總的來說,代碼會建議'personal_image.setIcon(new ImageIcon(f));'3)使用合乎邏輯的一致形式縮進代碼行和塊。縮進旨在使代碼的流程更易於遵循! –

+0

@ AndrewThompson - 是SIR,我從那裏刪除那個JLabel。這只是爲了獲得參考,我會讓它推測它已經存在。 SIR,也已經提到他使用NetBeans IDE。所以,他可能使用了NetBeans自動Swing處理的定義良好的功能。而且,SIR,另外OP的問題是如何使用JButton添加圖像到標籤----我提到他將如何處理這個邏輯。 –

+0

不,我在哪裏做的?請指出,你的'f'我已經改名爲'file'。 @JiunJye –