Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 19 of 19

Thread: adding ActionListeners dynamically

  1. #1
    Member Hikaros's Avatar
    Join Date
    Sep 2013
    Posts
    42
    My Mood
    Love
    Thanks
    10
    Thanked 2 Times in 2 Posts

    Question adding ActionListeners dynamically

    So i'm in a project where i need to build a Jmenu with its options dynamically, i have in a database table the structure of the entire menu and i have an idea in how to do it, however i don't have the slightest idea in how to add the actions listeners.

    Initially i was creating a menu statically and i was making anonimous classes for each actionListener in each JMenu Item but since i have to change it for what i mentioned before i have no idea how to do it, can you please show me an example in how to do that?


    going into the ActionListeners:
    I've been creating anonimous classes for each ActionListener of each button in each one of my JFrames (JInternal Frames)
    is this a wrong approach to it?


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: adding ActionListeners dynamically

    No idea what you're asking. What does, "add ActionListeners dynamically" mean? What does "build a Jmenu with its options dynamically" mean? Can you give examples of what you're trying to do? Show the changing JMenu items and describe how those changes impact the ActionListeners.

    Have you ever used a quality program where the menu items were constantly variable or moving around? If you have (and I'm doubtful), do you remember that as a good user experience? Have you migrated from the earlier Word versions (like 2000) to what we have now, 2010 or whatever the heck it is? How are you liking that?

  3. #3
    Member Hikaros's Avatar
    Join Date
    Sep 2013
    Posts
    42
    My Mood
    Love
    Thanks
    10
    Thanked 2 Times in 2 Posts

    Default Re: adding ActionListeners dynamically

    No idea what you're asking. What does, "add ActionListeners dynamically" mean?
    hahaha in runtime

    What does "build a Jmenu with its options dynamically" mean? Can you give examples of what you're trying to do? Show the changing JMenu items and describe how those changes impact the ActionListeners.

    Have you ever used a quality program where the menu items were constantly variable or moving around? If you have (and I'm doubtful), do you remember that as a good user experience? Have you migrated from the earlier Word versions (like 2000) to what we have now, 2010 or whatever the heck it is? How are you liking that?
    lol'd hahahahaha, i don't have anything against those, but is not what i want haha.
    i want to assamble a menu based off profiles, a profile creator will have every single menu item listed and the admin (or someone with priviledges) and will send the structure of how the menu > sub menu > menu item should go so then i the application can assamble a Jmenu Bar based off the options wanted in the profile built before.

    this code is not mine (i haven't coded my own just yet since i'm reading first) but this shows a bit of what i want to do.

    public class MenuPrincipal extends JFrame implements ActionListener {
     
    private static final long serialVersionUID = 1L;
    public static JDesktopPane desktop;
     
    public MenuPrincipal(ArrayList<MenuDTO> opcionesUsuario) {
         //Creamos la ventana del menu principal.
        super("Menu Principal - Demografo");
     
        JMenuBar menuBar = null;
        JMenu menu = null, submenu = null;
        JMenuItem menuItem = null;
     
        int longitud = opcionesUsuario.size();
     
        //Creamos una barra de menu
        menuBar = new JMenuBar();
     
        menu = new JMenu("Archivo");
        menuItem = new JMenuItem("Cerrar sessión",
            new ImageIcon("http://www.javaprogrammingforums.com/images/middle.gif"));
        menu.add(menuItem);
        menu.addSeparator();
        menuItem = new JMenuItem("Salir");
        menu.add(menuItem);
     
        MenuDTO menuDTO;
        for(int i = 0; i < longitud; i ++) {
            menuDTO = opcionesUsuario.get(i);
            if(menuDTO.getTieneHijos().equals("S")) {
                if(menuDTO.getIdPadre() == null) {
                    menu = new JMenu(menuDTO.getNombre());
                    menuBar.add(menu);
                }
                else {
                    submenu = new JMenu(menuDTO.getNombre());
                    menu.add(submenu);
                }
            }
            else {
                menuItem = new JMenuItem(menuDTO.getNombre());
                menuItem.setActionCommand(Integer.toString(menuDTO.getIdOpcion()));
                menuItem.addActionListener(this);
                menu.add(menuItem);
            }
        }
        desktop = new JDesktopPane();
        desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
     
        int inset = 50;
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        setBounds(inset, inset,
                  screenSize.width  - inset*2,
                  screenSize.height - inset*2);
        setContentPane(desktop);
        setJMenuBar(menuBar);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setExtendedState(MAXIMIZED_BOTH);
        setSize(450, 260);
        setVisible(true);
    }

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: adding ActionListeners dynamically

    hahaha in runtime
    Everything a program does is done at runtime.
    One question might be: what is the source of the Strings used in the menu items: literals coded in the program vs Strings read in from a file.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Member Hikaros's Avatar
    Join Date
    Sep 2013
    Posts
    42
    My Mood
    Love
    Thanks
    10
    Thanked 2 Times in 2 Posts

    Default Re: adding ActionListeners dynamically

    i have no idea how to explain it anymore lol, i said dynamically because it changes, it's never the same, is not as declaring the entire menu and its items statically, they would never change if coded it that way but i don't want that, i want to build a jmenubar, menu, items based off the structure in a database table, doing it that way it means i can have several menus structured by the user and not me.

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: adding ActionListeners dynamically

    Is this the approch that you are asking about:
    read the data
    use the data to control the building of the menu items.

    Instead of sequential statements, use if statements to control how the menu is built.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Member Hikaros's Avatar
    Join Date
    Sep 2013
    Posts
    42
    My Mood
    Love
    Thanks
    10
    Thanked 2 Times in 2 Posts

    Default Re: adding ActionListeners dynamically

    haha yeah, that is what i want to do, but i have no idea how to manage the ActionListeners of each item.

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: adding ActionListeners dynamically

    Can you explain? What does "manage an ActionListener" mean?
    When a listener is added to a menu item, pass its constructor all the data it needs.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: adding ActionListeners dynamically

    First, I suggest you suggest disable the menu items you don't want the current user to have access to. But if that's not good enough . . .

    Write a class that builds a menu or a number of menus in a collection based on a parameter sent to the constructor. Something like:
    public class BuildForumMenus extends Something
    {
        String accessLevel;
     
        // a constructor that takes one parameter that defines the access level
        public BuildForumMenus( String accessLevel )
        {
            // builds the menu(s)
        }
     
    }

  10. #10
    Member Hikaros's Avatar
    Join Date
    Sep 2013
    Posts
    42
    My Mood
    Love
    Thanks
    10
    Thanked 2 Times in 2 Posts

    Default Re: adding ActionListeners dynamically

    Quote Originally Posted by GregBrannon View Post
    First, I suggest you suggest disable the menu items you don't want the current user to have access to. But if that's not good enough . . .

    Write a class that builds a menu or a number of menus in a collection based on a parameter sent to the constructor. Something like:
    public class BuildForumMenus extends Something
    {
        String accessLevel;
     
        // a constructor that takes one parameter that defines the access level
        public BuildForumMenus( String accessLevel )
        {
            // builds the menu(s)
        }
     
    }
    i thought about it but that would suggest me creating the entire menu myself and just disable menu items depending on user's access level, but what i need to do is different. id like to do something like this:

    database table "menu_structure"

    menu1 | item1 | item2 | item3 | submenu | submenu item| etc
    menu2 | item1 | item2 | item3 | submenu | submenu item| etc

    and a method that would build a menubar based off that table with that structure.

    this is my fully functional code for what i do to build my menu from tables (right now is more than one, i will tweak it later on)

    tables:
    menu; fields; idmenu | menu
    submenu; fields; idsubmenu | idmenu | submenu
    menuitem; fields; idmenuitem | idmenu | idsubmenu | menuitem

    public JMenuBar createMenu(){
            JMenuBar bar = new JMenuBar();
            JMenu menu = null, submenu = null;
            JMenuItem menuItem = null;
     
            try{
                pstatement = connection.prepareStatement("select * from menu");
                ResultSet rsMenu = pstatement.executeQuery();
     
                while (rsMenu.next()){
                    menu = new JMenu(rsMenu.getString("menu"));
                    bar.add(menu);
     
                    pstatement = connection.prepareStatement("select * from submenu where idmenu = ?");
                    pstatement.setInt(1, rsMenu.getInt("idmenu"));
                    ResultSet rsSubMenu = pstatement.executeQuery();
     
                    while (rsSubMenu.next()){
                        if (!rsMenu.wasNull()){
                            submenu = new JMenu(rsSubMenu.getString("submenu"));
                            menu.add(submenu);
     
                            pstatement = connection.prepareStatement("select * from menuitem where idmenu = ? and idsubmenu = ?");
                            pstatement.setInt(1, rsMenu.getInt("idmenu"));
                            pstatement.setInt(2, rsSubMenu.getInt("idsubmenu"));
                            ResultSet rsMenuItem = pstatement.executeQuery();
     
                            while (rsMenuItem.next()){
                                menuItem = new JMenuItem(rsMenuItem.getString("menuitem"));
                                submenu.add(menuItem);
                            }
                        }
                    }
     
                    pstatement = connection.prepareStatement("select * from menuitem where idmenu = ? and idsubmenu is null");
                    pstatement.setInt(1, rsMenu.getInt("idmenu"));
                    ResultSet rsMenuItem = pstatement.executeQuery();
     
                    while(rsMenuItem.next()){
                        if (!rsMenuItem.getString("menuitem").equalsIgnoreCase("separador")){
                            menuItem = new JMenuItem(rsMenuItem.getString("menuitem"));
                            menu.add(menuItem);
                        }else{
                            menu.addSeparator();
                        }
     
                    }
     
                }
     
     
            }catch(SQLException ex){
                JOptionPane.showMessageDialog(null, ex);
            }
     
            return bar;
        }

    now the problem is: how do i add each item's action listener? i have no idea on what to do.

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: adding ActionListeners dynamically

    how do i add each item's action listener?
    call the item's addActionListener() method with a reference to an ActionListener object.

    Is the question: How to have useful code in the listener that is related to the menu items. How does the program know what to do when the menu items are "dynamically" added from a database? Would there need to be some pre-generated code saved as serialized objects that would be read from the database to be used as the actionlistener.
    If you don't understand my answer, don't ignore it, ask a question.

  12. #12
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: adding ActionListeners dynamically

    My thoughts for adding ActionListeners but not tried in this context: Either pair each menu item with an anonymous inner class ActionListener as you proposed earlier, or create an umbrella ActionListener that handles a number of menu items that belong to the same access level and pass that action listener to the method or class that creates the menus.

    I was also thinking that this might be a great opportunity to use an event bus design, but I haven't completely thought that through.

  13. #13
    Member Hikaros's Avatar
    Join Date
    Sep 2013
    Posts
    42
    My Mood
    Love
    Thanks
    10
    Thanked 2 Times in 2 Posts

    Default Re: adding ActionListeners dynamically

    i'm sorry but what is an umbrella ActionListener and what is an event bus design too? hahaha

    i thought about adding the actionListeners in the while iterator when adding every item but that means the code inside each action listener will have to be the same. is it possible to convert a string into something the compiler can read as commands? because if it is possible i was thinking about having in an ArrayList all of the things i want the actionlisteners to do.

    i still have no idea on what to do about how to add the different action listeners u_u

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: adding ActionListeners dynamically

    each action listener will have to be the same
    Not necessarily. You can use if statements to chose which action listener to add.
    if(cond1)
    add listener 1
    if(cond2)
    add listener 2

    etc

    I don't know how you can get the right listener code for a user selected menu item. Perhaps have a Map that connects the menu item to a listener.
    convert a string into something the compiler can read as commands
    Map<String, ActionListener>
    If you don't understand my answer, don't ignore it, ask a question.

  15. The Following User Says Thank You to Norm For This Useful Post:

    Hikaros (November 5th, 2013)

  16. #15
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: adding ActionListeners dynamically

    Have you tried anything yet? It seems you're making it too hard, and I don't agree that, "adding the actionListeners in the while iterator when adding every item means the code inside each action listener will have to be the same." If the menu items change to accommodate the user's access level, the actions wouldn't change for the menu items each user sees. Menu item to action should be a one-to-one relationship. If not, you might give an example where that would not be true.

    I used the imprecise term "umbrella" as a name for a single ActionListener than handles multiple menu items. Forgive me if I added confusion.

  17. #16
    Member Hikaros's Avatar
    Join Date
    Sep 2013
    Posts
    42
    My Mood
    Love
    Thanks
    10
    Thanked 2 Times in 2 Posts

    Default Re: adding ActionListeners dynamically

    Quote Originally Posted by GregBrannon View Post
    Have you tried anything yet? It seems you're making it too hard, and I don't agree that, "adding the actionListeners in the while iterator when adding every item means the code inside each action listener will have to be the same." If the menu items change to accommodate the user's access level, the actions wouldn't change for the menu items each user sees. Menu item to action should be a one-to-one relationship. If not, you might give an example where that would not be true.

    I used the imprecise term "umbrella" as a name for a single ActionListener than handles multiple menu items. Forgive me if I added confusion.
    i haven't coded anything yet trying to find out a way (reading here and there) to see what is probably the simplest, more than passing an access level, is a profile, with the profile i'll be selecting the way the menu is assambled (a change to be made to the tables), but there is still the problem to adding each action listener's code. and don't worry about the "umbrella" term lol i even googled it but didn't find anything, so i was just wondering xD

    Quote Originally Posted by Norm View Post
    Not necessarily. You can use if statements to chose which action listener to add.
    if(cond1)
    add listener 1
    if(cond2)
    add listener 2
    this sounds beautiful, i will go with this, now i have a question, is it possible to have a class with several action listeners in it? if so how is it declared? i tried looking in google but i didn't find anything like this. i thought that making anonimous classes in each if is an option but that would make the method that assambles the menu to be huuuuge so i thought itd be great if there is a way to have every action listener in a different class (a single one, not having different classes files).

  18. #17
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: adding ActionListeners dynamically

    is it possible to have a class with several action listeners in it?
    As internal classes.
    Why? Classes are cheap and easier.
    If you don't understand my answer, don't ignore it, ask a question.

  19. The Following User Says Thank You to Norm For This Useful Post:

    Hikaros (November 5th, 2013)

  20. #18
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: adding ActionListeners dynamically

    I'm disappointed and discouraged that you don't know the answer to that question. On the other hand, it's an indication that you need to write 40+ more programs that use ActionListeners from addActionListener( this ) to action listeners as anonymous inner class to creating your own action listener classes that handle specific types of actions before you're ready for this project.

    And haven't you seen an 'if' statement before? Odd.

  21. #19
    Member Hikaros's Avatar
    Join Date
    Sep 2013
    Posts
    42
    My Mood
    Love
    Thanks
    10
    Thanked 2 Times in 2 Posts

    Default Re: adding ActionListeners dynamically

    Quote Originally Posted by Norm View Post
    As internal classes.
    Why? Classes are cheap and easier.
    will do that then, thanks! :3

    Quote Originally Posted by GregBrannon View Post
    I'm disappointed and discouraged that you don't know the answer to that question. On the other hand, it's an indication that you need to write 40+ more programs that use ActionListeners from addActionListener( this ) to action listeners as anonymous inner class to creating your own action listener classes that handle specific types of actions before you're ready for this project.

    And haven't you seen an 'if' statement before? Odd.
    i've read 2 books, and i've seen at least over 200 java tutorials and none have mentioned the "why" is better one to another and how or when to pick the others, etc. everything i've coded so far have always had anonimous classes, that's why i ask D:

    and where did you get the "haven't you seen an 'if' statement before?" from? lol

    anyways that is why i asked on what was the best way to tackle several dozens of action listeners D:

Similar Threads

  1. Connecting Two Different ActionListeners
    By steme in forum Java Theory & Questions
    Replies: 1
    Last Post: April 26th, 2013, 08:35 AM
  2. Replies: 6
    Last Post: December 17th, 2012, 07:54 AM
  3. How to use multiple actionlisteners
    By pottsiex5 in forum AWT / Java Swing
    Replies: 9
    Last Post: November 19th, 2011, 09:37 AM
  4. Adding strings to an array dynamically, how can i do it?
    By emkoirl in forum What's Wrong With My Code?
    Replies: 3
    Last Post: April 8th, 2011, 02:07 PM
  5. [SOLVED] NullPointerException on ActionListeners
    By cherryduck in forum What's Wrong With My Code?
    Replies: 2
    Last Post: December 7th, 2010, 04:17 PM