I have a collection of objects descended from JComponent that are displayed on an object desended from JPanel.

Basically these JComponent-based objects are components that can be added and placed arbitrarily and can be dragged about on the panel. The panel is in charge of repainting all the tools/components that have been added to it and its paintComponent looks like this:

//inside the panel class...

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

    // draw the components
    for (GPComponent i : componentManager.getComponents()) {
		i.invalidate();
		i.repaint();
    }
}

Correspondingly the component object has a paintComponent method that draws up the component's appearance:

//inside the component class...

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    System.out.println("painting myself!");
    //draw appearance   
    ...

}

However this does not work! The components are not drawn. They are there, and can be moved, but they are invisible. That debug string never even appears! The only way to get the components to draw properly is to:
1) use i.paint(g) in the panel (rather than i.repaint()), and
2) change the component class's paintComponent(Graphics g) method to paint(Graphics g )

which it seems is an improper way of doing things because repaint() is delayed, which allows multiple rapidfire requests to me merged, etc. I thought repaint() calls update() which calls paint() which calls paintComponent()?!

Recommended Answers

All 4 Replies

applefat,
Post complete source code.

Thank you for your reply-- but, this is a fairly large project. There are dozens of files and classes. Everything worked by calling paint directly, but it's unnatural; I'm just trying to improve efficiency and maintainability and so on.

I think the problem is I'm missing an important concept here about repaint. I know that if I call repaint() within the panel itself, the panel's paintComponent() which I posted above is clearly called. Can one object NOT repaint another object to which it has no direct relation? Either through .add() or some other means?

On second thought, perhaps calling paint directly happens to be valid in this case, I mean surely for animations repaint could have some strange consequences...

I've had numerous problems with repaint () and they used to drive me nuts. I won't claim to understand the ins and outs, but I've gotten better. They have tended, for me at least, to boil down to my not using threading properly. Here is a thread that I started where that was an issue and which got solved for me by others' posts, particularly posts 9 and 11. This may be of some use to you.

http://www.daniweb.com/forums/thread178151.html

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.