什么是父组件以及子组件是什么?

时间:2014-08-11 21:37:46

标签: java swing

在谈到Swing的绘画时,我一直听到这两个词,但是,我不知道哪个是哪个。

据我所知,子组件是屏幕上已存在的组件(可以是JButtonJFrame或自定义绘图。并且父组件是接下来要添加/绘制的组件。 (因此,如果我们在绘画时覆盖paintChildren()方法,则屏幕上已有的组件不再出现。

有人可以为我验证这一点,因为我的头脑开始受到影响,LOL

1 个答案:

答案 0 :(得分:3)

enter image description here

意思可以概括为:

  • 父组件中包含其他组件。
  • 子组件包含在另一个组件中。

以下是创建上述图像的简单源代码。

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);
    }
}

  

..如果我们在绘画时覆盖paintChildren()方法,屏幕上已有的组件就不再出现了。

不要使用paintChildren()方法。在十多年的Swing开发中(包括很多自定义绘画示例),我需要完全覆盖它的0次。

对于从JComponent(通常是JPanel)延伸的Swing组件中的自定义绘制,我们会:

  • 覆盖paintComponent(Graphics)方法以进行自定义绘制。
  • 调用super.paintComponent(Graphics)方法以确保自定义组件的任何 子项或边框 都已绘制。