Quasi Abstraction of the JMenu system

Setting up the menu for JFrame is a matter of creating JMenuBar, JMenu, JMenuItem, add()-ing the components and setting ActionListener for JMenuItem.  The each menu item must be associated with the menu, and the menu must be associated with the menubar.  The ActionListener must be set for each menu item, and the ActionEvent must be processed appropriately.

This is a process that can be automated.  It would be far more easier if the menu item can be processed in some managed way.  There are ways of thinking on this: for smaller system, it would be more intuitive if the action is defined in the proximity of the menu item being declared.  In a larger system, it gets unmanageable unless all the accesses are not processed in a centralized manner.

→ JavaMenuMenu.java

Here I show a way that this procedure can be if not abstracted then greatly simplified by creating a menu class.  Here each menu items is associated with a tag.  A hashtable as the lookup table for the tag and the menu item.  The ActionEvent coming from JMenuItem will be processed at actionPerformed() of the component that implements the menu, most likely by JFrame.  All can be set just by calling a function (setMenu() in the code below).  Here is the file that sets the menu.

How you would use the file:

- Instantiate the menu.

    NewsMenu menu = new NewsMenu();

- Set the menu.

    menu.setMenu(this, this, Locale.US);

- Implement ActionListener.

    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();
        MENUITEM n = menu.comp.get(source);
        if (n != null) {
            switch (n) {
            case nNewsJSON:
                getJSON();
                break;
            case nNewsRSS:
                getRSS();
                break;
            case nNewsQuit:
                dispose();
                break;
            case nEditCopy:
                break;
            case nFilterKeyword:
                filter();
                break;
            case nHelpAbout:
                about();
                break;
            }
        }
    }


Download:


javamenu is a Java app that does all the above work for you.  If you are using Maven, download the project and run

    mvn package

The JAR file will be under target directory.

    java -jar javamenu-0.0.1-SNAPSHOT-jar-with-dependencies.jar

Usage:

Create a menu tree, and run Tools|Convert. The generated code will appear in the right pane. The actionPerformed() sample should appear in the bottom pane.




Comments

Popular posts from this blog

Logging your Maven project with Logback

TreeEditor: Customizing Drag and Drop

Spring Tool Suite