Reputation: 29
I keep hearing these two term when it comes to painting in Swing, however, I'm not sure which is which.
To my understanding is that the child components are the ones that already exist on screen (could be a JButton
, JFrame
, or custom painting) . and the parent components are the one to be added/drawn next. (hence, if we override the paintChildren()
method when painting, the components that were already on the screen don't appear any more).
Can someone validate this for me as my head is starting to hurt from thinking about, LOL
Upvotes: 0
Views: 1347
Reputation: 168825
The meaning can be summed up as:
Here is the simple source code that created the above image.
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).
Don't mess with the paintChildren()
method. In over a decade of Swing development (including a lot of custom painting examples), I've needed to override that exactly 0 times.
For custom painting in a Swing component that extend from JComponent
(typically a JPanel
) we would:
paintComponent(Graphics)
method to do custom painting.super.paintComponent(Graphics)
method to ensure that any children or borders of the custom component are painted.Upvotes: 3