2013-03-30 54 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方法...