任何人都可以向我解释一下paintComponent
方法吗?它的意思是什么?什么时候叫?它与paint
方法有什么不同?
请向w.r.t解释以下代码:
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);
}
答案 0 :(得分:2)
除了paint(...)之外,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方法...