Search code examples
javauser-interfacegraphicspaintpaintcomponent

nothing shows up in Java's paintComponent. How do I fix this?


In Java, I need to draw a simple line with the paintComponent. Here is my attempt, but nothing was shown when I executed the program. Please show me the correct way of doing this.

import javax.swing.*;
import java.awt.*;

public class DrawLine extends JPanel {

    public Illusion(Color backColor){
        setBackground(backColor);
    }

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.setColor(Color.black);
        g.drawLine(100, 100, 300, 100);
    }

}

Solution

  • Your painting a black line on a black background, so I'd say its working just fine. Try changing the color of the line

        g.setColor(Color.Red);
        g.drawLine(100, 100, 300, 100);
    

    Your also not taking into account the actual size of the panel, I'd do something more along the lines of

        g.drawLine(0, 0, getWidth(), getHeight());
    

    As a test

    You might like to have a read through