Search code examples
javaswingpaintcomponentjcomponent

Java paintComponent running but not showing


so I just want to paint a square in a random part of the screen as a custon JComponent:

public void paintComponent(Graphics g){
    Graphics2D g2d = (Graphics2D) g;
    if( this.good ){
        g2d.setColor(Color.green);
    }
    else{
        g2d.setColor(Color.red);
    }
    g2d.fillRect(this.x, this.y, this.w, this.h);
    System.out.println("painting");
}

here is the method that calls painting via repaint()

private void stateChange(){
        
    double rand = Math.random();
        
    if (rand < 0.5){
        this.good = !this.good;
    }
    setLocation(this.x,this.y);
    repaint();
}

this.x and this.y are constantly changing, but I know that works. When I run my code, it prints "painting" where it should, but nothing is showing up. Am I doing something wrong?

extra code:

here is what I put for trying to get it to show up:

\\in JComponent constructore
setOpaque(true);
setVisible(true);
setSize(this.w,this.h);

Solution

  • The problem, based on the example code you've provided, is the fact that you are actually painting out side of the bounds of viewable space of the component.

    When painting, the top, left corner of the Graphics context is 0x0, Swing has already translated the Graphics context based on the position of the component, so...

    g2d.fillRect(this.x, this.y, this.w, this.h);
    

    Is actually (possibly) painting beyond the viewable area of the component. For example, if the x position is 10 and y is 10, but height and width is only 10, 10, you are painting at position 10x10, which would be beyond the viewable space of the component, instead, you should try something like...

    g2d.fillRect(0, 0, this.w, this.h);
    

    Or, based on your example code,

    public void paintComponent(Graphics g){
        Graphics2D g2d = (Graphics2D) g;
        if( this.good ){
            g2d.setColor(Color.green);
        }
        else{
            g2d.setColor(Color.red);
        }
        super.paintComponent(g2d);
    }
    

    Instead....