0

I got a class that's supposed to launch a game (with main()), and the game's opening screen. The class with main() (named Starter), that extends JFrame, creates a new OpeningScreen class (extending JPanel), and adds it to the JFrame.

For some reason, the OpeningScreen won't be added to the JFrame. Code:

Starter class:

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

public class Starter extends JFrame {

    public Starter(){

        setSize(500,500);
        setResizable(false);
        setTitle("Ping-Pong Battle");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        OpeningScreen openingS = new OpeningScreen();
        add(openingS);

        setVisible(true);

    }

    public static void main(String[]args){
        Starter starter = new Starter();
    }

}

OpeningScreen class:

import javax.swing.*;

import java.awt.event.*;
import java.awt.*;

public class OpeningScreen extends JPanel {

    public OpeningScreen(){
        setBackground(Color.BLACK);
        setFocusable(true);
            setVisible(true);
    }

    public void paint(Graphics g){

        // Soon code here to be drawn.

    }

    public void startGame(){
        Board board = new Board();
    }

}

What's the problem? Thanks

EDIT: The constructor of OpeningScreen does run, but doesn't paint the background black. Also, trying to draw things in paint() doesn't work.

Andrew Thompson
  • 163,965
  • 36
  • 203
  • 405
Josh
  • 95
  • 1
  • 8

2 Answers2

2

I think because you override paint() the background doesn't get painted, so it appears like the Panel isn't added. Commenting out the paint method results in the Window being black for me.
Also, drawing in the paint method works for me, maybe your color is set to black so it doesn't show on the black background ? Try g.setColor(Color.white) before drawing.

2

Your problem arises from overriding paint in your OpeningScreen class. The background is not drawn because you never draw it! Call super.paint(g) to fix this.

However, it is generally recommended to use paintComponent() instead of paint(). Just move your code to paintComponent.

This method correctly draws a black background a red square:

@Override
public void paintComponent(Graphics g){

    super.paintComponent(g);
    g.fillRect(100, 100, 100, 100);
}
Community
  • 1
  • 1
ApproachingDarknessFish
  • 13,013
  • 6
  • 35
  • 73
  • Okay, forgot the super.paint(g). Thanks a lot :) – Josh Dec 29 '13 at 21:57
  • 2
    It is typically [recommended](http://docs.oracle.com/javase/tutorial/uiswing/painting/) to override `paintComponent` instead of `paint` as the preferred way of perfoming custom painting... – MadProgrammer Dec 29 '13 at 22:13