开发者

How to integrate a JMenuBar in an MVC architecture in Java?

I'm using this tutorial to build an application using the MVC architecture : http://www.oracle.com/technetwork/articles/javase/index-142890.html. But I'm not sure how or where should I put the code to build and add actionListener of a JMenuBar inside of it.

Furthermore, the book Object-Oriented Design & Patterns by Cay Horstmann say "The controller may process mouse and keyboard events from the windowing system, or it may contain user interface elements such as buttons and menus." Should I follow this advice, if yes,开发者_StackOverflow社区 how should I implement it ? How to add it to the JFrame that is in my Main class ?


As suggested in How to Use Actions, Action is a convenient way to encapsulate this. Moreover, Action "can be used to separate functionality and state from a component."

Addendum: In this very simple example, the model is a File representing a directory in a file system, and the view is a JLabel that listens for the actionPerformed(). The encapsulation afforded by Action ensures that each menu item and tool bar button produce the same result. The approach is emblematic of Swing's separable model architecture.


I've always created MenuBars in the following way.

class MyMenuBar extends JMenuBar {
   add(new FileItem())
}

class FileItem extends MenuItem {
    addMenuItem(new ExitAction())
}

class ExitAction extends AbstractAction {
    //define the action, tooltip and name of here
}

then in your main frame you just add the menubar to it JFrame myframe;

myFrame.setMenuBar(new MyMenuBar())

Some of this syntax might be wrong, haven't written a menubar in a while. You can further extend it by having factory classes that return your actions so they can be reusable or use some DI framework to do the same thing

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜