Reputation: 136
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();
}
Upvotes: 0
Views: 76
Reputation: 168825
public void paintComponents(Graphics g) {
super.paintComponents(g);
Should be:
public void paintComponent(Graphics g) {
super.paintComponent(g);
(no plural).
This way:
painting
string will appear (as many times as the API feels necessary to paint the component).Upvotes: 2
Reputation: 5712
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
Upvotes: 1