java 油漆()和油漆组件()之间的区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15103553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between paint() and paintcomponent()?
提问by Boogley Beegly
I have tried tutorials on this but I still don't quite understand it. Basically my question is which method is better and why? Should I use paint
or paintComponent
?
我已经尝试过这方面的教程,但我仍然不太明白。基本上我的问题是哪种方法更好,为什么?我应该使用paint
还是paintComponent
?
Please try to keep the answer simple, thanks.
请尽量保持答案简单,谢谢。
回答by christianhs
Quoting from documentation of paint()
method
引用paint()
方法文档
This method actually delegates the work of painting to three protected methods: paintComponent, paintBorder, and paintChildren. ... A subclass that just wants to specialize the UI (look and feel) delegate's paint method should just override paintComponent.
该方法实际上将绘制工作委托给三个受保护的方法:paintComponent、paintBorder 和paintChildren。... 只是想专门化 UI(外观和感觉)委托的绘制方法的子类应该只覆盖paintComponent。
It looks like the paint()
method actually draws the component, including the border and children. If you only want to customize the component's appearance excluding the border and children, you use paintComponent()
.
看起来该paint()
方法实际上绘制了组件,包括边框和子组件。如果您只想自定义组件的外观,但不包括边框和子项,您可以使用paintComponent()
.
http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#paint(java.awt.Graphics)
http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#paint(java.awt.Graphics)
回答by MadProgrammer
Generally speaking, when painting in Swing, it is recommended to override paintComponent
.
一般来说,在 Swing 中绘画时,建议覆盖paintComponent
.
There are a number of reasons why, one is paintComponent
is painted at the bottom layer, meaning you won't accidentally wiping out any components that were rendered during the paint process - this happens a lot to people who post here.
有很多原因,一个是paintComponent
在底层绘制,这意味着您不会意外擦除在绘制过程中渲染的任何组件 - 在这里发帖的人经常发生这种情况。
There are a, very, few times you might need to override paint
, but I would always encourage you to try making it work with paintComponent
first.
有很多次您可能需要覆盖paint
,但我总是鼓励您首先尝试使其工作paintComponent
。
Check out
查看
- Performing custom painting
- Painting in AWT and Swing(+1 to trashgod)
- 执行自定义绘画
- 在 AWT 和 Swing 中绘画(+1 到垃圾神)