2014-03-29 71 views
-1

嗨,我創建其中二我有JLabel我希望把更多然後1個圖像上JLabel,也是一個Java桌面應用程序想寫殲標籤上的一些文字如何在jlabel上設置圖像?

ImageIcon icon1 = new ImageIcon("Images/YourCompanyLogo.png"); 
    ImageIcon icon2 = new ImageIcon("Images/Your.png"); 
    // In init() method write this code 
    jLabelYourCompanyLogo.setIcon(iconLogo); 

我怎樣才能做到這一點?

我想提前後招呼

由於這2個圖標添加到JLabel

+2

標籤只能顯示1個圖標。從這兩張圖片中製作一張圖片,或使用2張標籤。 –

+0

我可以使用1個圖像和文本 – user3456343

+0

@JBNizet或者覆蓋它的'paintComponent'方法使其顯示多個圖像 – BackSlash

回答

0
String path = "(Insert your path here)" 

你有你的圖片移動到你的項目,這意味着這裏的一切你的代碼和資料都會保存項目中。 然後你創建另一個文件夾f.e調用res代表資源和你保存你想要加載的所有圖片。 然後,如果你得到了這個它看起來像這樣:

String path = "/res/(Your picture name DONT FORGET .png or .jpg ending)" 

圖片應該是PNG或JPG!

然後回到編碼: ü創建一個新的URL稱爲URL和其他的東西

Url url; 
ImageIcon ii; 
Image image; 

然後在類的構造函數ü寫:

url = getClass().getResource(path); 
ii = new ImageIcon(url); 
image = ii.getImage(); 

然後,你需要第二個方法你可以撥打

public void paintComponent(Graphics g){ 
    g.drawImage(url,imageX,imageY,null); 
} 

而且在你的班級的頂部你imp ORT

import java.awt.Graphics; 
import java.net.URL; 
import java.awt.Image; 
import javax.swing.ImageIcon; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
1

你可以使用Compound Icon,它允許你將兩個或多個圖標合併成一個。

或者,只需創建一個JPanel(使用適當的佈局管理器)並添加兩個JLabel到面板。

也想寫一些文字,殲標籤上

參見:Image Background and Text Alignment 4的方法來做到這一點。