2013-03-30 55 views
-2

任何人都可以請解釋我的paintComponent方法嗎?這是什麼意思?當它被調用?與paint方法有什麼不同?我不明白paintComponent方法

請解釋WRT下面的代碼:

public RoundButton(String label) { 
    super(label); 

// These statements enlarge the button so that it 
// becomes a circle rather than an oval. 
    Dimension size = getPreferredSize(); 
    size.width = size.height = Math.max(size.width, 
     size.height); 
    setPreferredSize(size); 

// This call causes the JButton not to paint 
    // the background. 
// This allows us to paint a round background. 
    setContentAreaFilled(false); 
    } 

// Paint the round background and label. 
    protected void paintComponent(Graphics g) { 
    if (getModel().isArmed()) { 
// You might want to make the highlight color 
    // a property of the RoundButton class. 
     g.setColor(Color.lightGray); 
    } else { 
     g.setColor(getBackground()); 
    } 
    g.fillOval(0, 0, getSize().width-1, 
     getSize().height-1); 

// This call will paint the label and the 
    // focus rectangle. 
    super.paintComponent(g); 
    } 
+2

請閱讀此內容 - [在AWT和Swing中繪畫](http://www.oracle.com/technetwork/java/painting- 140037.html) - 因爲它在本文中都有解釋。 –

+1

投票結束,因爲您最好通過閱讀與上面相關的教程來回答這個問題,而不是讓我們中的一個無力地嘗試重新編寫教程。 –

回答

2

Jcomponent中有油漆旁邊3層其他塗料的方法(...):

paintComponent() 
paintBorder() 
paintChildren() 

這些方法被稱爲在paint方法在這(來自Jcomponent塗裝方法的代碼):

 if (!rectangleIsObscured(clipX,clipY,clipW,clipH)) { 
     if (!printing) { 
     paintComponent(co); 
     paintBorder(co); 
     } 
     else { 
     printComponent(co); 
     printBorder(co); 
     } 
      } 
    if (!printing) { 
     paintChildren(co); 
    } 
    else { 
     printChildren(co); 
    } 

當改變組件的方式就像在你的例子中一樣,總是覆蓋paintComponent()方法。在你的例子中,在調用super.paintComponent()之前繪製一個橢圓。 更改邊框的相同帳戶,您只需重寫paintBorder方法...