开发者

Updating button states in a Java Swing application

I've implemented a basic Swing GUI based on the concept of a playlist as part of a larger DJ audio mixing application (think a primitive Virtual DJ(!)). The playlist basically consists of a JTable onto which tracks can be tracks can b开发者_开发百科e dragged n' dropped from a JTree. The JPanel that incorporates the table also contains a suite of buttons for saving, loading, and deleting playlists as well as for loading the player(s). These button states need to be updated (enabled/disabled) based on the current state of the application (i.e. is a playlist loaded? Are there tracks in the playlist? etc.)

I'm trying to follow an MVC pattern whereby the underlying TableModel is separated from the table and button UI through a controller.

My question is...What is the most elegant/efficient way to handle the button updates? At the moment, a reference to the currently loaded playlist file is stored in the controller, and the controller determines whether a playlist is empty from the model. It then sends two boolean values (isEmpty, isLoaded) to the View, which then determines which buttons to enable based on these values. This method seems a little inelegant, so I'd welcome any suggestions.

Thanks!


As I understand MVC, theoretically:

  1. Controller updates the model
  2. View reads the model and updates itself

The problem in practice is that your domain model (your classes) is not the same as Swing Model classes. So the question is who is syncing domain and swing models: Controller or View?

  1. Controller syncs them. When domain data changes (playlist is empty or not) Controller pushes changes to View. In this case Controller is more complex and is dependent on both domain model and Swing Model. Also this model becomes complex when you have one domain model and multiple views (Tree and Table showing same underlying data).

  2. View adapts to domain model. When domain model data changes, Controller simply indicates to View that it should update itself. In this case View is dependent on domain classes, but Controller is not dependent on Swing Model or View, except that it requests an update.

As I see you implemented option 1.

Personally I'd use option 2., where Controllers deal with business logic and domain model and View deals with syncing to domain model and building up view hierarchy.


You can do this more elegantly using listeners and Actions. Use an AbstractAction for each button. (You can reuse them for menu items as well.) Then you can enable/disable the action and the button will update to match. If you add a TableModelListener to your table model it will be notified of all changes and can make the updates to the actions.

You won't be creating your own MVC. You will be using the inherent MVC in the Swing classes themselves.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜