Ms.Sahin
Ms.Sahin

Reputation: 101

paintComponents method not being called in Java

I watched a tutorial and tried to do same thing, I wrote the codes exactly the same but it shows nothing. I think it is because paintComponent method is not being called, I also tried to print something to console by paintComponent.

Here is my code:

public class Line extends JPanel{

    @Override
    public void paintComponents(Graphics g){
        super.paintComponent(g);
        g.setColor(Color.red);
        g.drawLine(100, 10, 30, 40);

    }
    public static void main(String[] args) {
        Line l =new Line();

        JFrame myFrame = new JFrame("Line");
        myFrame.setSize(600, 400);        
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.add(l);
        myFrame.setVisible(true);
    }
}

Thank you!

Upvotes: 3

Views: 59

Answers (1)

Arnaud
Arnaud

Reputation: 17534

What you want to override is paintComponent, not paintComponents with a s .

paintComponents paints the child components of the current component (well it sort of tells the child components to paint themselves on the Graphics object).

paintComponent paints the component itself, this is the method you want to override to do custom painting for your component.

Upvotes: 3

Related Questions