Search code examples
javaswingjcomponent

PaintComponent don't seem to get call or to show


My problem is really simple : I have this little program, and it just don't show the red box I'm trying to make :

Main

public class Main {
    public static void main(String[] args) {
        Affichage a = new Affichage();
        a.setVisible(true);
    }
}

Affichage :

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

public class Affichage extends Frame{
    public Affichage(){
        setTitle("Exo 1 : Galerie");
        setSize(1120,560);
        Graphique graph = new Graphique();
        this.add(graph);
    }
}

Graphique :

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

public class Graphique extends JComponent {
    @Override
    public void paintComponents(Graphics g) {
        super.paintComponents(g);
        Graphics pinceau = g.create();

        pinceau.setColor(Color.RED);
        pinceau.fillRect(100, 100, 200, 200);

        System.out.println("test");
    }
}

I bet it's ridicule but I can't find what it is, help me. PS : yes the test don't get print too


Solution

  • You are adding a Swing component (javax.swing.JComponent) to an AWT frame (java.awt.Frame). Noone will call the paintComponents() method, that's why you don't get any output or result. Extend from javax.swing.JFrame instead, so you have a Swing frame with a Swing component.