Java中的JPanel vs JFrame [英] JPanel vs JFrame in Java
问题描述
我正在学习Java gui。我学习创建窗口的方法是继承或扩展 JFrame
类,最好使用它,因为 JFrame
包含Window的所有属性。现在,如果我想在此窗口中添加内容,我需要使用 add()
方法。但今天我遇到了 JPanel
,它还创建了一个窗口,我们可以通过 jpanelObjec.add()
添加内容。
I am learning Java gui. The way I learnt to create a window is to inherit or Extend JFrame
class and it is good to use it, as JFrame
contains all the properties of a Window. Now If I want to add something to this window, I need to use add()
method. But Today I came across JPanel
which also creates a windows and we can add stuff by jpanelObjec.add()
.
这两种方法有什么区别?它们是否有某种关联?
What is the difference between the two methods? Are they somehow related?
推荐答案
你不应该扩展 JFrame
类不必要的(仅当您在 JFrame
类中添加额外功能时)
You should not extend the JFrame
class unnecessarily (only if you are adding extra functionality to the JFrame
class)
JFrame :
JFrame
extends Component
和容器
。
JFrame
extends Component
and Container
.
它是一个顶级容器,用于表示窗口的最低要求。这包括边框
s,可恢复性( JFrame
可调整大小?),标题栏,控件(最小化/最大化允许? ),以及各种事件
的事件处理程序,如 windowClose
, windowOpened
等。
It is a top level container used to represent the minimum requirements for a window. This includes Border
s, resizability (is the JFrame
resizeable?), title bar, controls (minimize/maximize allowed?), and event handlers for various Event
s like windowClose
, windowOpened
etc.
JPanel :
JPanel
extends Component
, Container
和 JComponent
JPanel
extends Component
, Container
and JComponent
这是一个泛型类,用于将其他组件
组合在一起。
It is a generic class used to group other Component
s together.
-
使用
LayoutManager
时,这很有用。GridLayout
fi将组件添加到不同的JPanel
,然后将其添加到JFrame
创建gui。它在布局
和可重用性方面更易于管理。
It is useful when working with
LayoutManager
s e.g.GridLayout
f.i adding components to differentJPanel
s which will then be added to theJFrame
to create the gui. It will be more manageable in terms ofLayout
and re-usability.
在Swing中绘画/绘图时,你会覆盖 paintComponent(..)
当然还有双缓冲的全部乐趣。
It is also useful for when painting/drawing in Swing, you would override paintComponent(..)
and of course have the full joys of double buffering.
没有顶级容器就不能存在Swing GUI ( JWindow
, Window
, JFrame
Frame
或 Applet
),但可能没有 JPanel
s。
A Swing GUI cannot exist without a top level container like (JWindow
, Window
, JFrame
Frame
or Applet
), while it may exist without JPanel
s.
这篇关于Java中的JPanel vs JFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!