How do I program a dynamic menu in Swing?

Basically, I want the user to be able to save bookmarks, which are then placed in a list in a submenu in the menu bar. As I will program the generic function for any number of bookmarks that can be added, I basically want the elements to put the URL in the text box when clicked. Do I need to create a new class for this, or is there a built-in function?

My program is a simple RSS reader written in Java using Swing.

+3
source share
1 answer

You need to add the MenuListener to the menu item that you want to be dynamic. In the void menuSelected (MenuEvent e) method, implement submenu building. In the first implementation, you can first reset the contents of your menu, and then rebuild it from scratch, rather than updating it:

JMenu menu = new JMenu("Bookmarks");
menu.addMenuListener(new MyMenuListener());

private class MyMenuListener implements MenuListener {

    public void menuCanceled(MenuEvent e) { }

    public void menuDeselected(MenuEvent e) { }

    public void menuSelected(MenuEvent e) {
        JMenu menu = (JMenu) e.getSource();
        populateWindowMenu(menu);
    }
}

void populateWindowMenu(JMenu windowMenu) {
    windowMenu.removeAll();
    // Populate the menu here
}
+5
source

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


All Articles