Search code examples
javajpanelrepaintredraw

Repaint issue with JPanel inside another JPanel


I'm drawing shapes inside this JPanel, which is also inside another main JPanel. At repaint() it only draws the shapes for one millisecond and then they disappear. They don't stay painted, why?

My paintComponent method is something like this

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);

    for (int i = 0; i < reportElements.size(); i++) {
        this.reportElements.get(i).display((Graphics2D) pageComponents.get(i).getGraphics());

    }
}

When the parent is a JEditorPane with setEditable() enabled, it works and we can see the shapes but when it's a JPanel, after a millisecond all I see is empty panels.


Solution

  • in this case what happens to those pageComponents, the small JPanels? The parent panel is not gonna draw the shapes on them is it?

    I'm not sure I undertand your comment. Your main panel should contain child panels. The child panels should be added to the main panel using a layout manager. Then when Swing decides to repaint the main panel, it will also repaint all the child panels and in turn the child panels will repaint there shapes.

    For what its worth Custom Painting Approaches has a working example of drawing shapes on a panel.