[RESOLVIDO] Montagem dinâmica de menus em uma JMenuBar

2 respostas
marcos.9306

estou fazendo um sistema baseado em plugins, e gostaria que esses plugin pudessem criar entradas de menu numa barra de menus e numa barra de ferramentas. A barra de ferramentas foi tranquila, mas estou enfrentando um pequeno problema nos menus:
minha lógica é mais ou menos assim:

numa classe existe um método chamado addMenuEntry(String key, ImageIcon icon, ActionListener listener, String pluginID);
key -> no formato “Menu#SubMenu1#SubMenu2#…#Item De Menu” deu pra entender né?
icon -> o ícone da entrada, ou null caso não exista ícone
listener -> o event handler da entrada
pluginID -> o id do plugin que criou a entrada, será usada para o sistema de login e permissões

se por exemplo uma entrada “Menu#Consultar#Clientes” e uma outra “Menu#Consultar#Produtos” for adicionada, na segunda vez(Produtos), apenas o item deverá ser criado.

os plugin realizam a interface Plugin, que tem o método initPlugin(), aqui é que os menus devm ser criados

tentei duas formas de fazer, mas ambas não deram certo, alguém me dá uma luz??

desde já mt obrigado

2 Respostas

Marky.Vasconcelos

Talvez a classe Plugin podia ter um método getMenu() que depois de inicializado ele pega esse menu.

marcos.9306

AE!!

Consegui! Ficou um pouco grande, fato, mas levando em consideração que tenho que apresentar isso daqui à tres semanas, funcionar é o suficiente =)
Da forma como fiz, basta passar uma entrada como “Ferramentas#Opções#Geral” que ele vai automaticamente criar os menus e submenus(caso seja necessário) e criar um item de menu, com o listener, ícone e texto.

Vou deixar o código aqui, caso alguém precise =)

A classe MenuEntry

class MenuEntry {

    public static final int NONE = -1;
    public static final int MENU_ENTRY = 0;
    public static final int MENUITEM_ENTRY = 1;

    private String key;
    private String pluginID;
    private JMenu menu;
    private JMenuItem item;
    private int entryType;

    public MenuEntry(String key, String pluginID, JMenu menu, JMenuItem item) {
        this.key = key;
        this.pluginID = pluginID;
        this.menu = menu;
        this.item = item;
        entryType = NONE;
    }

    public MenuEntry() {
        this(null, null, null, null);
    }

    /**
     * @return the key
     */
    public String getKey() {
        return key;
    }

    /**
     * @param key the key to set
     */
    public void setKey(String key) {
        this.key = key;
    }

    /**
     * @return the pluginID
     */
    public String getPluginID() {
        return pluginID;
    }

    /**
     * @param pluginID the pluginID to set
     */
    public void setPluginID(String pluginID) {
        this.pluginID = pluginID;
    }

    /**
     * @return the menu
     */
    public JMenu getMenu() {
        return menu;
    }

    /**
     * @param menu the menu to set
     */
    public void setMenu(JMenu menu) {
        this.menu = menu;
        this.entryType = NONE;

        if(this.menu != null) {
            this.entryType = MENU_ENTRY;
            this.item = null;
        }
    }

    /**
     * @return the item
     */
    public JMenuItem getItem() {
        return item;
    }

    /**
     * @param item the item to set
     */
    public void setItem(JMenuItem item) {
        this.item = item;

        this.entryType = NONE;

        if(this.item != null) {
            this.entryType = MENUITEM_ENTRY;
            this.menu = null;
        }
    }

    public int getEntryType() {
        return this.entryType;
    }
}

E a classe MainFrame

public class MainFrame extends JFrame {

    // os objetos
    private static JMenuBar menuBar;
    private static JToolBar toolBar;
    private StatusBar statusBar;
    private static JDesktopPane desktop;
    private static ArrayList<MenuEntry> menuEntries;

    static {
        menuBar = new JMenuBar();
        toolBar = new JToolBar();
        menuEntries = new ArrayList<MenuEntry>();
    }

    /**
     * O Construtor
     * @param controller
     */
    public MainFrame() {
        super();
        initComponents();
    }

    /**
     *
     */
    private void initComponents() {
        ...
    }


    public static void addMenuEntry(String key, ImageIcon icon, ActionListener listener, String pluginId) throws UIBuildException {

        // checando se a chave já existe
        if (hasEntry(key)) {
            throw new UIBuildException("The entry " + key + " already exists.");
        }

        // pegando as chaves
        String keys[] = key.split("#");

        // checando o tamanho da lista
        if (keys.length == 0) {
            throw new UIBuildException("Invalid entry.");
        }

        for(int i=0 ; i< keys.length ; i++) {
            String currentKey = generateName(keys, i+1);
            MenuEntry entry = new MenuEntry();
            entry.setKey(currentKey);
            entry.setPluginID(pluginId);

            if(i>0 && i == (keys.length - 1)) { // verificando se é a última entrada da chave(o item de menu)
                if(!hasEntry(currentKey)) {
                    JMenuItem item = new JMenuItem();
                    item.setText(keys[i]);
                    item.setIcon(icon);
                    item.addActionListener(listener);
                    entry.setItem(item);
                }
            }
            else {
                if(!hasEntry(currentKey)) { // caso contrário é um menu
                    JMenu menu = new JMenu();
                    menu.setText(keys[i]);
                    menu.addActionListener(listener);
                    entry.setMenu(menu);
                }
            }
            addMenuEntry(entry);
        }
    }

    /**
     *
     * @param entry
     */
    private static void addMenuEntry(MenuEntry entry) {
        if(!hasEntry(entry.getKey())) { // só processar a nova entrada se ela não estiver na lista
            menuEntries.add(entry);

            // verificando se é o menu principal
            if(entry.getKey().split("#").length == 1) {
                menuBar.add(entry.getMenu());
                System.out.println("Adding Main Menu: "+entry.getKey());
            }
            else {
                // pegando a entrada anterior(o menu ou submenu)
                MenuEntry e = getEntry(generateName(entry.getKey().split("#"), entry.getKey().split("#").length -1));

                // adicionando o item de menu ao submenu
                if(entry.getEntryType() == MenuEntry.MENU_ENTRY)
                    e.getMenu().add(entry.getMenu());

                else if(entry.getEntryType() == MenuEntry.MENUITEM_ENTRY)
                    e.getMenu().add(entry.getItem());
            }
        }
    }

    /**
     *
     * @param key
     * @return
     */
    private static boolean hasEntry(String key) {
        if(getEntry(key) != null)
            return true;
        return false;
    }

    /**
     * 
     * @param key
     * @return
     */
    private static MenuEntry getEntry(String key) {
        for (int i = 0; i < menuEntries.size(); i++) {
            if (menuEntries.get(i).getKey().startsWith(key)) {
                return menuEntries.get(i);
            }
        }
        return null;
    }

    /**
     * Gera o nome da entrada
     * @param keys
     * @param range
     * @return
     */
    private static String generateName(String[] keys, int range) {
        String name = "";
        String sep = "#";
        for (int i = 0; i < range; i++) {
            sep = "#";

            if (i == 0) {
                sep = "";
            }

            name += sep + keys[i];
        }
        return name;
    }

    public static void addToolBarButton(JButton button, String pluginId) {
        ...
    }
}
Criado 11 de agosto de 2009
Ultima resposta 11 de ago. de 2009
Respostas 2
Participantes 2