当谈到在 Swing 中绘画时,我不断听到这两个术语,但是,我不确定哪个是哪个。
据我了解,子组件是屏幕上已经存在的组件(可以是 JButton
、JFrame
或自定义绘画)。父组件是接下来要添加/绘制的组件。 (因此,如果我们在绘制时重写 paintChildren()
方法,屏幕上已经存在的组件将不再出现)。
有人可以帮我验证这一点吗,因为我的头开始因为思考而受伤,哈哈
最佳答案
其含义可以概括为:
- 父组件内部还有其他组件。
- 子组件包含在另一个组件中。
这是创建上述图像的简单源代码。
import java.awt.*; // package import for brevity
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class ParentAndChildComponent {
public JComponent getGUI() {
JPanel p = new JPanel(new GridLayout(1,0,20,20));
p.setBorder(new TitledBorder("Panel: Child of frame/Parent of labels"));
for (int ii=1; ii<4; ii++) {
JLabel l = new JLabel("Label " + ii + ": Child of panel & frame");
p.add(l);
}
return p;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
JFrame f = new JFrame("Frame: Parent of all other components");
f.setContentPane(new ParentAndChildComponent().getGUI());
f.pack();
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
<小时/>
..if we override the
paintChildren()
method when painting, the components that were already on the screen don't appear any more).
不要乱用paintChildren()
方法。在十多年的 Swing 开发(包括许多自定义绘制示例)中,我需要重写它 0 次。
对于从 JComponent
扩展的 Swing 组件(通常是 JPanel
)中的自定义绘制,我们会:
- 重写
paintComponent(Graphics)
方法以进行自定义绘制。 - 调用
super.paintComponent(Graphics)
方法以确保绘制自定义组件的任何子项或边框。
关于java - 什么是父组件,什么是子组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25252853/