views:

142

answers:

3

Hi, I am a new to programming with Java and I would like to know if there is some common practice for managing state of opened document (is current state saved or dirty) , saving document, opening, creating new document and so on. How do you approach this?

Right now I have my little Swing application and have actions for opening and closing document and creating new one, but I don't know how to manage if user has saved file or not (I need this to check if user wants to create new one or open existing while working on current.)

Is there some pattern for this? All advices are very welcome since I am still learning how to swim with Java.

A: 

You may think about working with temporary versions of your document (i.e. you open main document, but when you edit it then temp document is created). In this case another user who opens the same document will see original doc. As I know it's common practice..

But I'm not sure that you want to maintain so complex behavior..

Roman
+1  A: 

You have a boolean variable named isDirty which starts at false.

Every time a change is made to the document it is set to true by the code.

All other program functions (Open,save,new menus e.t.c) check the status of this boolean before doing anything else.

This way they also present the familiar dialogs: Are you sure you want to exit, Discard your changes e.t.c

I have used this several times on real world Swing Apps

kazanaki
+2  A: 

As far as I know Swing does not have mechanisms for managing document state. You have to do that yourself. But then, it is not that much code that has to be written and if you have several different documents in your app you can put that stuff in an abstract base class.

The basic approach has been outlined already: just have a "dirty" flag in your document data structure. You should put some thought into writing down which of your operations like "create", "open", "save", "close" should modify and evaluate this flag. I would suggest a state chart (not necessarily the UML state machine variant) as a tool to specify this.

If you need more complex functionality, especially undo/redo, take a look at the Memento pattern. Most of the code that has to be written when you use this pattern is specific to the application and its data structures (i.e. the types you create for managing documents) so it would be hard to impossible to effectively generalize this and put it into a framework like Swing or RCP.

Robert Petermeier