简体   繁体   中英

Calling two classes that are dependent on each other in another class? -Java GUI

I'm trying to restart my game after clicking a button.

This is supposed to get two screens to show up, one after the other, and those two screens are defined in two classes that are dependant on each other.

But the problem is that the first class (WordPuzzle) uses another object from the second class (Skeleton), rather than the one that I have called, while the Skeleton class I have called works as usual.

The variable tries sets up how many times the WordPuzzle object should run.

And gain is an integer that comes from the Skeleton class.

The class WordPuzzle needs an integer (from Skeleton) and a Skeleton object in order to be initialized.

The Skeleton class needs a WordPuzzle object.

 //define variables
 Skeleton window;



 //Inside actionPerformed

  WordPuzzle puzzlegame = new WordPuzzle(window.gain, window); // creates puzzle window but does not make it visible yet
  puzzlegame.tries = 0; //set number of tries back to 0
  puzzlegame.getContentPane().setBackground(Color.WHITE);

  //ERROR: THE VALUES FOR CONSONANTGAIN COME FROM ANOTHER SKELETON OBJECT

  Skeleton window = new Skeleton (puzzlegame);
  window.getContentPane().setBackground(Color.WHITE);
  window.setVisible (true);

  this.dispose();

I hope this is familiar to you guys, I'm absolutely stumped. Thank you C:

Edit: Although I picked the best answer, this was actually resolved after tranfering the code to the main and calling that from here.

First i see that you have an un-initialized variable but i assume somehow you called it from somewhere ele and initialised it.

 Skeleton window;
`

//Inside actionPerformed

Here you are creating a puzzlegame with window from skeleton, that's ok.

  WordPuzzle puzzlegame = new WordPuzzle(window.gain, window); // creates puzzle window but does not make it visible yet
  puzzlegame.tries = 0; //set number of tries back to 0
  puzzlegame.getContentPane().setBackground(Color.WHITE);

Now skeleton is being created with puzzlegame and puzzlegame has skeleton window because puzzlegame was created with Skeleton window . You should created another window here and give that window as parmater. In java you can use new keyword that creates a new object.

Skeleton window = new Skeleton (new WordPuzzle()); //Here you need a new object
  window.getContentPane().setBackground(Color.WHITE);
  window.setVisible (true);

  this.dispose();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM