2013-11-27 46 views
0

我在繪製一些圖像時遇到了一些問題。 我正在使用JDialog來顯示背景和分離的類來顯示卡(使用精靈)。背景上的油漆部件

背景顯示不錯,但JPanel不顯示。

這裏是我的代碼:

public Main(java.awt.Frame parent, boolean modal) { 
    super(parent, modal); 
    initComponents(); 

    //Call the board to draw cards 
    Board plateau = new Board(); 

    this.add(plateau); 
} 

/** 
* Paint the background 
* 
* @param g 
*/ 
@Override 
public void paint(Graphics g) { 
    try {  
     Graphics2D g2 = (Graphics2D) g; 

     this.background_image = ImageIO.read(new File(this.background)); 
     Graphics2D big = this.background_image.createGraphics(); 
     Rectangle rectangle = new Rectangle(0, 0, 20, 20); 
     g2.setPaint(new TexturePaint(this.background_image, rectangle)); 

     Rectangle rect = new Rectangle(0, 0, this.getWidth(), this.getHeight()); 
     g2.fill(rect); 
    } catch (IOException ex) { 
     Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); 
    } 
} 

和應吸取的卡類:

@Override 
public void paint(Graphics g) { 
    try { 
     this.image = ImageIO.read(new File("Ressources/images/cardsprite.gif")); 

     //4 lines 
     for (int i = 0; i < 4; i++) { 
      //13 rows 
      for (int j = 0; j < 13; j++) { 
       //Split one card 
       BufferedImage temp = this.image.getSubimage(j * this.CARD_WIDTH, 
         i * this.CARD_HEIGHT, this.CARD_WIDTH, this.CARD_HEIGHT); 

       g.drawImage(temp, j * this.CARD_WIDTH, 
         i * this.CARD_HEIGHT, this); 
      } 
     } 


    } catch (IOException ex) { 
     Logger.getLogger(Board.class.getName()).log(Level.SEVERE, null, ex); 
    } 

如果我把卡拉絲級到主的paint方法,它工作正常。

我錯過了什麼嗎?

謝謝

回答

0

從本質上講,你破壞了油漆鏈,這是防止任何畫它的「主」類的孩子。

首先查看Painting in AWT and Swing瞭解油漆工藝的概況。

你也不應該壓倒paint,而是應該覆蓋的東西,覆蓋paintComponent

查看Performing Custom Painting瞭解更多詳情。

基本上,您應該創建一個「背景」面板,負責繪製背景,然後添加負責在其上繪製卡片的組件,確保它是透明的(setOpaque(false)),以便背景通過顯示。

如果你沒有做任何動態效果,你甚至可以爲我們的背景窗格JLabel

您應該避免在任何可能會耗費時間的paintXxx方法中執行任何操作,例如加載圖像。油漆工藝應該進行優化,使其儘可能快地運行...