Search code examples
javarepaintjcomponent

Proper way for Repainting JComponent


So, I've taken an AP class on java, and in the class, we never really went over repaint(), and how to properly use it. I've also searched through the internet, and I personally have not found any answers on the standard way of calling repaint(). Are we supposed to call the repaint() method from the main class like the following?

import java.awt.*;
import javax.swing.*;

public class RepaintExample{

    public static void main(String[] args){

        JFrame frame = new JFrame();
        JComponent component = new JComponent();
        frame.add(component);
        frame.repaint();
    }

}

Or would I call the JComponent.repaint() Like this

import java.awt.*;
import javax.swing.*;

public class RepaintExample{

    public static void main(String[] args){

        JFrame frame = new JFrame();
        JComponent component = new JComponent();
        frame.add(component);
        component.repaint();
    }

}

Or, are both approaches wrong, and JComponent.repaint() should be called from the paintComponent as shown here:

import java.awt.*;
import javax.swing.*;

public class ComponentRepaintExample extends JComponent{

    public void paintComponent(Graphics g){

        //Draw stuff
        for(int i = 0; i < 10; i++){
            //Draw stuff
            this.repaint();
        }
    }

}

It is quite possible that all three approaches are wrong. Any help figuring out how to properly use the repaint() method is appreciated. The whole topic is very shrouded to me, so I apologize if any terminology I use is incorrect. All thanks in advance.


Solution

  • Why do you think you need to call repaint()?

    The repaint() method is invoked by a Swing component automatically when a property of the component is changed.

    For example if you have a JLabel and you invoke setText(...) or setIcon(...), then those methods will automatically invoke repaint().

    You would NEVER invoke repaint() from a painting method.

    If you are doing custom painting, then your code should be structured like any other Swing component. That is you create getter/setter methods for your custom components to change properties of the component. In the setter method you invoke repaint().