repaint method is doing nothing once called

91 views Asked by At

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();
}
2

There are 2 answers

2
Andrew Thompson On BEST ANSWER
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).
0
Thusitha Thilina Dayaratne On

Here you have just create an instance of the MyLabel. Therefore your sout in the constructor get called and prints hello. Normally in swing repaint() method get trigger either by system event or a app-event. But since you have just create an instance and not placing it anywhere no event get triggered.
you can read up on Painting in AWT and Swing