I want to create a window with Java Swing. The window will have a menu bar with a File->Open button from where the user can select a file from hid hard drive. Th开发者_高级运维e File menu should also have a list of the most recent opened items, like many other applications show. Does anyone know what is the best approach?
I would suggest using the Preferences
class to persist the most recently opened items. That way, if the user restarts the application the items will still be available.
Note that on Windows the Preferences
class stores data in the registry, which is how many native Windows applications store and retrieve recently open file names.
Also, note that the Preferences class simply acts as an API for storing and retrieving (key, value) pairs. You will still need to decide how you wish to store the information, and be responsible for dynamically building / updating the JMenu
when a new file is accessed. To accomplish this I would suggest implementing a Action
(extend AbstractAction
) to deal with when the user attempts to open a file. When the Action
runs it should persist the newly accessed file's name to the Preferences
class and dynamically rebuild the File JMenu
(in addition to opening the file).
精彩评论