关键点解释
-
**
Component
是根类**
所有 Swing 组件(如按钮、窗口、面板)的“老祖宗”都是Component
类。- **
JButton
、JFrame
、JPanel
本质都是Component
**。
- **
-
继承关系
- **
Container
继承自Component
**(Container
是Component
的子类)。 - Component(所有组件的基类)
- └── Container(可以装其他组件的容器)
└── JFrame(窗口)、JPanel(面板)等 -
为什么
showMessageDialog
的第一个参数可以是JButton
或JFrame
?- 因为它们都是
Component
的子类,而parentComponent
参数类型是Component
。 - 对话框会根据传入的
Component
自动找到其所在的顶级窗口,并居中显示实际效果
- 如果传入
button
,对话框会出现在按钮所在的窗口中央。 - 如果传入
frame
,对话框会直接出现在frame
窗口中央。 - 如果传入
null
,对话框会显示在屏幕中央(无父窗口)。 -
一句话总结
所有 Swing 组件都是
Component
,所以JButton
、JFrame
、JPanel
都能作为对话框的父组件参数!你的理解非常到位!👏
- 因为它们都是
- **