Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 538
Ms.Sahin Avatar asked Jun 19 '26 17:06

Ms.Sahin


1 Answers

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.

like image 185
Arnaud Avatar answered Jun 22 '26 06:06

Arnaud