2014-10-30 30 views
0
添加圖像

我的問題是,當我創建或使用獲取錯誤輸出中的JFrame

public void paint(Graphics g) 

{}

方法,我得到一個黑色的屏幕,而不是繪製的JFrame圖像圖像問題的代碼片段是

ImageIcon i=new ImageIcon("logo.png); 
Image im=i.getImage(); 
public void paint(Graphics g) 
{ 
g=getGraphics(); 
} 

請給我建議的替代方法或解決我的問題 在此先感謝

+0

您應該瞭解Java如何將值傳遞到方法中... – nem035 2014-10-30 15:29:51

回答

2

你會考慮使用JPanel並重寫paintComponent方法嗎?類似這樣:

BufferedImage image = ... //i'll leave this blank since there are several ways to get a bufferedimage. I'll leave an eg: ImageIO.read(new File("/path/to/image")); 
     JPanel pane = new JPanel() { 
     @Override 
     protected void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      g.drawImage(image, 0, 0, null); 
     }}; 

然後將面板添加到您的框架。您可以對JFrame中的容器執行相同的操作。邏輯是simillar。

+0

您是否也可以告訴我爲什麼 setBackground()方法在JFrame中不起作用? – Priyank 2014-10-30 16:11:32

+0

它不?你怎麼用它?在JFrame中,您必須設置容器的背景,而不是框架本身。 like:frame.getContentPane()。setBackground(Color.BLACK); 這是你問的嗎? – XFCC 2014-10-31 11:00:58

+0

Yessss這是錯誤,非常感謝... :-) – Priyank 2014-11-01 13:40:27