Search code examples
javaswingjlabeljava-2d

repaint method is doing nothing once called


I am trying to understand how repaint and paintComponents work in Java Swing, and wondering why this program only display "hello" when it's executed.

class MyLabel extends JLabel{

    private static final long serialVersionUID = 1L;

    public MyLabel(){
        System.out.println("hello");
        repaint();
    }

    @Override
    public void paintComponents(Graphics g) {
        super.paintComponents(g);
        System.out.println("painting");
    }
}

    public static void main(String[] args) {
         MyLabel lbl = new MyLabel();
}

Solution

  • public void paintComponents(Graphics g) { 
      super.paintComponents(g); 
    

    Should be:

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

    (no plural).

    This way:

    • The paint chain is not broken.
    • The painting string will appear (as many times as the API feels necessary to paint the component).