This code adds the user's favorited songs to a JmenuItem from an ArrayMap

        public void actionPerformed(ActionEvent evt) {
    String cmd = evt.getActionCommand();
    if (cmd != null) {
        if (cmd.equalsIgnoreCase("Favorite song")) {
            Music.f.add(Music.s);
            System.out.println(Music.s + " added to favorites");
            System.out.println(Music.f + " current list");

        }
    }
}
    public void initUI() {
    try {
    //...

        JMenu fileMenu = new JMenu("Music And Sound Options");
        JMenu favorites = new JMenu("Favorite songs");

        for (String name : Music.f) {
            JMenuItem menuItem = new JMenuItem(name);
            menuItem.addActionListener(this);
            favorites.add(menuItem);
        }


        JMenuBar menuBar = new JMenuBar();
        JMenuBar jmenubar = new JMenuBar();

        frame.add(jmenubar);
        menuBar.add(favorites);
        frame.getContentPane().add(menuBar, BorderLayout.NORTH);
        frame.pack();
        frame.setVisible(true); // can see the client

        init();
        //...
    } catch (Exception e) { e.printStackTrace(); }
}

I want the list of songs to update after a song is added, instead of having to restart the client to see more songs

有帮助吗?

解决方案

//JMenu favorites = new JMenu("Favorite songs");    
favorites = new JMenu("Favorite songs");

The Favorites menu needs to be defined as a class variable. Then when you do this your ActionListener can now reference the menu and add a new menu item to the menu.

if (cmd.equalsIgnoreCase("Favorite song")) {
    Music.f.add(Music.s);
    System.out.println(Music.s + " added to favorites");
    System.out.println(Music.f + " current list");
    JMenuItem item = new JMenItem(...);
    favorites.add( item );

其他提示

If you store a reference to your JMenuBar as a class field, you can call menuBar.removeAll() and repopulate it with new menu items whenever you want (though make sure you do it on the Swing thread when you do, using SwingUtilities.invokeLater() or your Swing method of choice).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top