2011-01-05 18 views
1

我有一個關於爲什麼我的圖像不顯示在我的程序背景中的查詢。我的意思是我做了所有必要的步驟,但仍然不會顯示。代碼運行完美,但沒有顯示圖像。該目錄被寫入圖像的良好位置。我用gui使用java。如果有人可以幫助我解決我的問題,我將不勝感激:)這裏是下面的代碼:java gui圖像問題:不顯示在後臺

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class hehe extends JPanel{ 

    public hehe(){ 

      setOpaque(false); 
      setLayout(new FlowLayout()); 
      } 

    public static void main (String args[]){ 
      JFrame win = new JFrame("yooooo"); // it is automaticcally hidden 

      JPanel mainPanel = new JPanel(new BorderLayout()); 
       win.add(mainPanel); 

    JLabel titleLabel = new JLabel("title boss"); 
      titleLabel.setFont(new Font("Arial",Font.BOLD,18)); 
      titleLabel.setForeground(Color.blue); 
      mainPanel.add(titleLabel,BorderLayout.NORTH); 

      win.setSize(382,269); // the dimensions of the image 
      win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      win.setVisible(true); 
     } 


      public void paint(Graphics g) { 

         Image a = Toolkit.getDefaultToolkit().getImage("C:\\Users\\andrea\\Desktop\\Gui\\car"); // car is the name of the image file and is in JPEG 
       g.drawImage(a,0,0,getSize().width,getSize().height,this); 
       super.paint(g); 
      } 
      } 

回答

1

在您提供的代碼中,沒有引用main()方法中的hehe類。我猜你會想創建該對象並將其添加到您的窗口。

你也需要包括在文件名的jpg擴展

+0

做了擴展,我會嘗試創建對象 – thegamer 2011-01-05 13:33:58

+1

也許你應該用你的新代碼更新這個問題 – 2011-01-05 13:42:40

+0

你的意思就是像這樣:hehe c = new hehe(); //跳過一行win.add(c);這是你的意思嗎? – thegamer 2011-01-05 13:48:55

1

super.paint()畫的圖像繪製後,背景和圖像隱藏。 嘗試setOpaque(false)或在繪製圖像之前更改調用super.paint()的順序。

也避免在paint()方法中獲取圖像。油漆經常被調用,所以你每次都在paint()上讀取圖像。爲圖像創建一個字段並在創建時讀取一次。

+0

setOpaque(假)已經假,U意味着設置是真的嗎?它仍然沒有桌面背景。我試圖把super.paint()放在行開始之前 - 圖像a - - 和行開始 - g.drawImage .. _但仍然沒有效果。我很困惑。 – thegamer 2011-01-05 13:33:35

+0

dw解決了它:) – thegamer 2011-01-05 18:14:21