0

I am trying to make a simple pong game in order to learn Java's JFrame, JPanel etc. I've seen people with similar problems but no solution seems to work, when I run the code all I see is an empty screen, at this point not even a simple conditional seems to work. Adding code here:

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

public class Pong extends JFrame {

        int ancho = 800;
        int alto = 800;
        Point barra1 = new Point((int) (ancho*0.05), (int) alto/2);
        Point barra2 = new Point((int) (ancho*0.95), (int) alto/2);
        boolean gameover = true;
        Pintar pintar;
    
    public Pong(){
         setTitle("Pong");
         Pintar elementos = new Pintar();
         this.getContentPane().add(elementos);
         setSize(ancho,alto);
         this.setBackground(null);
         this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         JFrame.setDefaultLookAndFeelDecorated(false);
         setUndecorated(true);
         this.setLocationRelativeTo(null);
         setVisible(true);
    }

    public class Pintar extends JPanel{
    
        public void pintar(Graphics g){
            super.paintComponent(g);
             if(gameover == true){
                 g.setColor(Color.BLACK);
             }
             else{
                 g.setColor(Color.WHITE);
             }
             g.fillRect(0, 0, ancho, alto);
         }
    }

    public static void main(String[] args) {
        Pong pantalla1 = new Pong();
    }
}

Anything I try seems to have no result, the painting settings are really simple now, if game over is false, it will paint a white square over the whole screen, otherwise, it will paint it black.

So I think the problem is on these graphics getting into the frame.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • You should be overriding `Pintar.paintComponent` (see Javadocs for `JPanel` [or superclass]) – g00se Oct 04 '21 at 10:25

1 Answers1

1

Your pintar method should not attempt to draw things.

Use the dedicated paintComponent method instead :

@Override
public void paintComponent(final Graphics g) {

    super.paintComponent(g);

    if (gameover == true) {

        g.setColor(Color.BLACK);

    } else {
        g.setColor(Color.WHITE);

    }

    g.fillRect(0, 0, ancho, alto);

}
Arnaud
  • 17,229
  • 3
  • 31
  • 44