1

I am quite sure that having this amount of code that I have my Main class should be able to show black background and other things that I wrote down and described in my Gameplay class but it doesn't.

My Main class:

package brickbraker;

public class Main extends Gameplay {

    public static void main(String[] args) {
        JFrame obj = new JFrame();
        Gameplay gamePlay = new Gameplay();
        obj.setBounds(10, 10, 700, 600);
        obj.setTitle("Brick Breaker");
        obj.setResizable(false);
        obj.setVisible(true);
        obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        obj.add(gamePlay);
    }

}

And here is my 2nd class:

package brickbraker;

public class Gameplay extends JPanel implements KeyListener, ActionListener {
    private int playerX = 310;
    private int ballPosX = 120;
    private int ballPosY = 350;
    private int ballXdir = -1;
    private int ballYdir = -2;

    public Gameplay() {
        addKeyListener(this);
        setFocusable(true);
        setFocusTraversalKeysEnabled(false);     
    }

    public void paint(Graphics g) {
        // background
        g.setColor(Color.black);
        g.fillRect(1, 1, 692, 592);       

        // borders
        g.setColor(Color.yellow);
        g.fillRect(0, 0, 3, 592);
        g.fillRect(0, 0, 692, 3);
        g.fillRect(691, 0, 3, 592);

        // the paddle
        g.setColor(Color.green);
        g.fillRect(playerX, 550, 100, 8);

        // the ball
        g.setColor(Color.yellow);
        g.fillRect(ballPosX, ballPosY, 20, 20);
    }
}
Dmitriy Popov
  • 2,150
  • 3
  • 25
  • 34
Michał Śniady
  • 119
  • 3
  • 14
  • 4
    Possible duplicate of [Why shouldn't I call setVisible(true) before adding components?](https://stackoverflow.com/questions/10790457/why-shouldnt-i-call-setvisibletrue-before-adding-components) – Tom Jun 30 '19 at 18:04

1 Answers1

1

Firstly, when you add a component to a visible container, you have to call repaint and revalidate methods. So after obj.add(gamePlay); do obj.repaint(); and obj.revalidate();. In your case, you could easily obj.add(gamePlay); and then obj.setVisible(true); in order to avoid using repaint and revalidate.

Secondly, in Gameplay class, you @Override paint method instead of paintComponent method. It should be:

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g); //Always call super when overriding paint component
    //Custom painting
}

Finally, Swing applications should run in their own thread called EDT (Event dispatch thread). Use SwingUtilities#invokeLater in order to do it. Something like:

SwingUtilities.invokeLater(() -> {
    JFrame obj = new JFrame();
    Gameplay gamePlay = new Gameplay();
    obj.setBounds(10, 10, 700, 600);
    obj.setTitle("Brick Breaker");
    obj.setResizable(false);
    obj.setVisible(true);
    obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    obj.add(gamePlay);
});
George Z.
  • 6,643
  • 4
  • 27
  • 47