2012-04-19 95 views
0

我想在框架中間繪製背景圖像。由於我的形象並不像窗戶那樣大,我想把黑色的背景。Java - 繪製背景問題

這裏是我使用的代碼:

public void paint(Graphics g) 
{ 
    if(this.background != null) 
    { 
     int bounds_top = getHeight()/2; 
     int bounds_left = getWidth()/2; 
     int half_height = this.background.getHeight(null)/2; 
     int half_width = this.background.getWidth(null)/2; 
     g.drawImage(this.background, bounds_left - half_width, bounds_top - half_height, this.background.getWidth(null), this.background.getHeight(null), this); 

     this.setBackground(Color.black); 
     //this.setOpaque(false); 
    } 
} 

如果我設置的幀中要被opaqe,則顯示我的圖像而背景爲灰色。 如果我將不透明設置爲false,則我的框架只是黑色,不會顯示圖像。

所以,這是我的問題,我如何顯示我的形象和背景背景?

回答

0

我發現了一個痘痘技巧來解決這個問題:

Graphics2D g2 = (Graphics2D) g; 
g2.setPaint(Color.BLACK); 
g2.fill(new Rectangle2D.Double(0, 0, getWidth(), getHeight())); 
g.drawImage(this.background, bounds_left - half_width, bounds_top - half_height, this.background.getWidth(null), this.background.getHeight(null), this); 

這種運作良好。

1

您正在將圖像繪製到背景,然後將背景顏色設置爲黑色。嘗試先將背景顏色設置爲黑色,然後將圖像繪製到其上。否則,它看起來像是在圖像上繪製黑色。

+0

我試圖把setBackground放在drawImage之前,但它給了我以前的結果 – Manitoba 2012-04-19 14:00:19

3

如果您是在JPanel子項中執行此操作,請在構造函數中調用setBackground(Color.black);,然後在paintComponent中執行代碼,首先調用super.paintComponent(g);作爲黑色背景。