I've got a problem with Swing, I'm trying to understand how the paintComponent works and I just don't get why in this case it gets called twice or even thrice (it seems to be randomly called to me).

package paintComponentTest;

import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class UI {

public static void main(String[] args) {
    JFrame testFrame = new JFrame();

    TestPanel testPanel = new TestPanel();
    testFrame.setContentPane(testPanel);

    testFrame.setSize(500, 500);
    testFrame.setVisible(true);
}
}

class TestPanel extends JPanel {

@Override
public void paintComponent(Graphics g) {
    System.out.println("Called");
}
}    

I'm working on a different project and my paintComponent also gets called several times whereas I'd like it only to be called once and it prevents me from going forward.

Thanks in advance !

有帮助吗?

解决方案

Basically, painting is outside of your control and there is (very little) you can do about.

paintComponent is called (indirectly) when the repaint manager decides that the component needs to be re-painted because of some event, such as the component been re-sized (directly or because the parent container was resized) or it has become displayable (now visible on the screen or added to a component that is displayable) and any number of system events.

The first thing you need to do (apart from calling super.paintComponent before you do any custom painting) is to relinquish the illusion of control you might think you have over the paint process.

Next, you should read through Painting in AWT and Swing and understand how the painting process works.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top