0

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

Andrew Thompson
  • 163,965
  • 36
  • 203
  • 405

2 Answers2

1

Actually, don't extend JFrame as it is bad practice. Just make an instance of it. To paint, extend JPanel and override paintComponent.

JFrame f = new JFrame();
f.add(new MyPanel());

class MyPanel extends JPanel {
   // other stuff
   public void paintComponent(Graphics g) {
       super.paintComponent(g);  
       // painting stuff.
   }
}

And remember not to mix Swing and AWT components.

WJS
  • 22,083
  • 3
  • 14
  • 32
0

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.

Progman
  • 13,123
  • 4
  • 28
  • 43
  • 1
    @LucaAntoine You should use `paintComponent()` (without the "s"), see https://stackoverflow.com/questions/9389187/difference-between-paint-paintcomponent-and-paintcomponents-in-swing – Progman Feb 28 '20 at 22:41