Welcome to the CSC Q&A.
Get help and give help!
Write great code!
It is our choices... that show what we truly are, far more than our abilities.

Categories

+18 votes

I want to pass the instance of the ProjectData object in the first window class to the second window class without creating another instance of it. We use a Project Data object in many places in both windows, but I want it to be the same ProjectData object.

asked in CSC285_Fall2018 by (100 points)

2 Answers

+9 votes
 
Best answer

Two potential approaches:

1) Have each controller pass the ProjectData object along to the next controller (See the Day14DemoOpenNextWindow project inside the SharedClassRepo -- it passes a String from one window to the next, but you can do the same thing with ProjectData.)

2) Use something like the Singleton pattern (as we talked about in class), where you change it so that the ProjectData constructor is private (so the only place you can create a ProjectData object is inside the ProjectData class), and create a private static field named currentProject and a couple public static methods:

a) ProjectData.openCurrentProject(File ...) which creates a new ProjectData object and stores it in the currentProject field.
b) ProjectData.getCurrentProject() that returns the currently loaded project object

After that pattern is used, then every Controller can simply call ProjectData.getCurrentProject() when they need access to the same project object, and they don't have to pass it along to each other...

answered by (1.4k points)
selected by
0

I added "project.getCurrentProject()" every time i need to access the ProjectData object but it gives me a warning saying " The static method getCurrentProject() from the type ProjectData should be accessed in a static way" every single time I use "project.getCurrentProject()" . Did I do something wrong?

+10 votes

You can pass your project data across as a parameter. If you're sending it to be used in a specific method, just add a ProjectData parameter.

Most controllers have an initialize method, so that would possibly be the most appropriate place to pass in that parameter

answered by (100 points)
...