matt matt - 7 months ago 12
Java Question

Am I calling the other classes correctly? I feel like the SnakeBoardDisplay should only be created once

I have 3 separate classes in Java one is for logic, one is painting, and the last is for the window.

Window Class, this class also creates a board display and adds to the window class

public SnakeWindow()
{
this.setTitle("Snake");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(win_wid, win_hei);

SnakeBoardDisplay dPanel = new SnakeBoardDisplay();
this.add(dPanel);
inintMenu();
this.setVisible(true);
setResizable(false);
}
public static void main(String[] args) {

new SnakeWindow();


}


Board Display Class, This class creates a new board display

Where is the proper place for this class to be called and executed?

public SnakeBoardDisplay()
{

game = new SnakeGame();

tm.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public static void main(String[] args) {

new SnakeBoardDisplay();


}


Game Class

public SnakeGame()
{
init();

}

public void init()
{
for(int i = 0; i < tokens; i++)
{
int q = i;

q *= seperationDis;


tokensx[i] = CRDX-q;
tokensy[i] = CRDY;

}
sideCollision();
appleCollision();
snakeMover();
bodyCollision();
apple();
}


Declaring the classes

public class SnakeGame extends SnakeWindow {

public class SnakeBoardDisplay extends JPanel implements ActionListener, KeyListener{

public class SnakeWindow extends JFrame {

Answer

Your main class is SnakeBoardDisplay. This class has the main method that instantiates the SnakeGame in SnakeBoardDisplay.

You mentioned:

SnakeGame extends SnakeWindow

Which means when the SnakeGame is instantiated, SnakeWindow is also created. You need to call the super class constructor in SnakeGame constructor.

public SnakeGame()
{
  super(); 
  init();
}