此代码将用户最喜欢的歌曲从 ArrayMap 添加到 JmenuItem
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(); }
}
我希望在添加歌曲后更新歌曲列表,而不必重新启动客户端以查看更多歌曲