开发者

Accessing Swing components of another class

开发者 https://www.devze.com 2023-01-23 22:06 出处:网络
I have two classes gameWindow and gameEngine. The Main method is in gameWindow class & so is the swing GUI code. Now, I want to access the swing components in gameEngine. How to do that? I always

I have two classes gameWindow and gameEngine. The Main method is in gameWindow class & so is the swing GUI code. Now, I want to access the swing components in gameEngine. How to do that? I always get the cannot find symbol error when I try it normally. I've tried making the components public but with no luck.

Also, I tried creating a instance of gameWindow but it too, didn't help. It compiled without any error but I got a BIG runtime error(which I can't even see, the command prompt gets开发者_JS百科 scrolled to it's limit).

RELP!!

P.S.: I don't think the posting the code here will help.


In order to access the components of gameWindow in gameEngine you need a reference to it. So I assume that GameWindow class creates the instance of GameEngine. Then you can do something like this:

 public class GameEngine{
      GameWindow window;

      public GameEngine(GameWindow gm){
           window = gm;
      }
      //rest of your code
 }

 public class GameWindow(){

     //At the point where you create the GameEngine
     GameEngine ge = new GameEngine(this);
     //rest of your code


}

Now GameEngine has a reference to the GameWindow that it can use.

Having said that, I would advise that you consider a different design. Having GameEngine directly access the GameWindow sounds as if the wrong classes are responsible for the wrong things. Maybe you might try looking at using some sort of Observer such that the GameWindow looks for changes in the GameEngine then accesses the updates and modifies the view accordingly. So the GameEngine does not have to access the swing components of GameWindow.


Pass a reference to gameEngine in the contructor or use a getter/setter type method.

For example, in gameWindow, when you create the gameEngine class, have a constructor that takes a gameWindow variable.

gameEngine:


gameWindow theMainWindow = null; public gameEngine(gameWindow mainWindow) { theMainWindow = mainWindow; }


Vincent's answer is correct, but involves instantiating GameWindow which the post said gives an error. I would advise redirecting your error stack trace to a file, reading it and troubleshooting your runtime error, then following his instructions.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号