2013-05-27 324 views
2

我有一個主類擴展了一個JFrame,然後JFrame添加一個jpanel。然後我嘗試設置jpanel的背景顏色,但無濟於事。根據我在google上發現的情況,我不確定問題出在哪裏,只需在JPanel中設置setBackground(Color)即可解決此問題,但似乎無法解決問題。此外,其他修補程序爲setOpaque(true)setVisible(true),或者使用getContentPane().setBackground(Color)形成JFrame但這些都不起作用。任何建議將非常感激,如果您需要更多信息,或有其他建議,請隨時爲我提供啓發。 :) 主類是:Java Jpanel,無法設置背景顏色

public class main extends JFrame{ 

    private Content content; 

    public main(){ 

     content = new Content(400, 600); 

     this.setTitle("Shooter2.0"); 
     this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     this.setResizable(false); 
     this.getContentPane().add(content); 
     this.getContentPane().setBackground(Color.BLACK); 
     this.pack(); 
     this.setVisible(true); 
     try{ 
      Thread.sleep(10000); 
     }catch(Exception e){} 
    } 


    public static void main(String[] args){ 
     main game = new main(); 
    } 

} 

和內容類:

public class Content extends JPanel{ 

    private viewItem ship; 

    public Content(int w, int h){ 
     this.setPreferredSize(new Dimension(w, h)); 
     this.setLayout(new BorderLayout());  
     this.createBattlefield(); 
     this.setOpaque(true); 
     this.setBackground(Color.BLACK); 
     this.repaint(); 
     this.setVisible(true); 
    } 

    public void createBattlefield(){ 
     ship = new viewItem("bubble-field.png", 180, 550, 40, 42);  
    } 

    public void paint(Graphics g){ 
     g.setColor(Color.BLACK); 
     this.setBackground(Color.BLACK); 
     ship.draw(g);  
    } 

} 

回答

5

你覆蓋paint無需調用

super.paint(g); 

這可以防止的背景和子組件從被繪。

對於搖擺覆蓋paintComponent代替風俗畫,並充分利用Swing的優化油漆模式,與@Override註釋和調用super.paintComponent(g)

Performing Custom Painting

+0

這樣的作品,爲什麼它是一個壞主意,覆蓋塗料(G)? – samuraiseoul

+0

'paintComponent'使用雙緩衝,所以更高性能。 – Reimeus

+0

好吧,謝謝你哦! – samuraiseoul

0

更換代碼塊

public void paint(Graphics g){ 
    g.setColor(Color.BLACK); 
    this.setBackground(Color.BLACK); 
    ship.draw(g);  
} 

通過

public void paintComponent(Graphics g){ 
    super.paintComponent(g); 
    g.setColor(Color.BLACK);   
    ship.draw(g);  
} 

要設置JPanel的背景色的構造,所以沒有需要它的paintComponent (){}方法...

試試上面必將代碼工作....