您不需要 Canvas 或 JPanel 来绘制吗?
我一直认为 Canvas 或 JPanel 是在 JFrame 上放置图形所必需的,但是我之前看到一个视频,其中该人在扩展 JFrame 时使用paint(graphics g) 并且没有制作面板或画布.如果是这种情况,为什么人们还要费心制作 Canvas 或 JPanel?
I have been under the impression that a Canvas or a JPanel were necessary to put graphics on a JFrame, however I saw a video earlier in which the person was using paint(graphics g)while extending JFrame and hadn't made a panel or a canvas. If this is a case, why do people bother with making a Canvas or a JPanel?
推荐答案
JFrame
扩展自 Frame
,扩展自 Window
,扩展来自 Container
,扩展自 Component
,它定义了 paint
.
JFrame
extends from Frame
, which extends from Window
, which extends from Container
, extends from Component
which defines paint
.
如果是这样,为什么人们还要费心制作 Canvas 或 JPanel?
If this is a case, why do people bother with making a Canvas or a JPanel?
要回答这个问题,您需要更好地了解 JFrame
(以及基于窗口的类).
To answer that question, you need to have a better understanding of JFrame
(and window based classes).
JFrame
实际上是一个复合组件,也就是说,它由许多提供窗口核心功能的其他组件组成
JFrame
is actually a composite component, that is, it's made of a number of other components which provide the core functionality of the window
这意味着,如果您覆盖 paint
并在框架上执行自定义绘制,您很可能会在子组件上绘制或者子组件将在其上绘制,并且因为绘制子系统的工作方式,在没有调用框架的绘制方法的任何时候都会这样做.
What this means is, if you override paint
and perform custom painting on the frame, it's very possible that you will paint over the child components or the child components will paint over it, and because of the way the paint subsystem works, will do so any time without the frame's paint method been called.
框架包括其可用区域内的窗口装饰.这意味着可见"面积实际上小于框架的定义面积.
Frame's include the window decorations within their available area. This means that the "viewable" area is actually smaller then the defined area of the frame.
这也是为什么推荐使用 pack
而不是 setSize
This is also why it's recommend to use pack
instead of setSize
这意味着如果您覆盖 paint
,您实际上可以在窗口装饰下进行绘画(是的,这种情况一直都在发生,我们已经厌倦了回答它)
This means that if you override paint
you could actually paint under the window decorations (yes, this happens all the time, and we're tired of answering it)
屏幕截图来自 如何设置中间?
JFrame
的 contentPane
负责这一点,因为它布置在可视区域内.
The contentPane
of JFrame
takes care of this, as it's laid out within the viewable area.
顶级容器,如 JFrame
不是双缓冲的,因此,即使您克服了上述所有问题,您也会得到闪烁的更新.当然你可以设计"你有自己的双缓冲算法,但在 Swing 中(即 JPanel
),它是免费的,何必呢
Top level containers, like JFrame
aren't double buffered, so, even if you overcome all of the above, you will get updates which flicker. Sure you could "devise" you're own double buffering algorithm, but in Swing (ie JPanel
), it's free, so why bother
作为一般建议,我们通常不鼓励从 JFrame
(或其他顶级容器)进行扩展,因为它会将您锁定在单个用例中并阻止重复使用的可能性.
As a general recommendation, we generally discourage extending from JFrame
(or other top level containers) as it locks you into a single use case and prevents the possibility of re-use.
另一方面,如果您使用 JPanel
,您可以随时将其添加到您想要的任何容器中
On the other hand, if you use a JPanel
, you can add it to what ever container you want, when ever you want
相关文章