How to integrate JMenuBar in MVC architecture in Java?

I use this tutorial to create an application using the MVC architecture: http://www.oracle.com/technetwork/articles/javase/index-142890.html . But I'm not sure how and where I have to put the code for the assembly and add an ActionListener JMenuBar to it.

In addition, the book Object-Oriented Design and Patterns, written by Kay Horstman, says: "The controller can handle mouse and keyboard events from the window system or it can contain user interface elements such as buttons and menus." Should I follow this advice, if so, how do I implement it? How to add it to a JFrame, which is in my main class?

+6
source share
2 answers

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

Application: in this very simple model, it is File , which represents a directory in the file system, and the view is JLabel , which listens for actionPerformed() . The encapsulation provided by Action ensures that every menu item and toolbar button gets the same result. This approach symbolizes the structure of a shared Swing model .

+3
source

I have always created MenuBars as follows.

 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 JFrame myframe menu bar to it;

 myFrame.setMenuBar(new MyMenuBar()) 

Some of these syntaxes may be incorrect if you did not write a menu at the time. You can extend it by adding factory classes that return your actions so that you can reuse them or use some DI frameworks to do the same.

0
source

Source: https://habr.com/ru/post/887849/


All Articles