我正在使用此代码从文本文件加载JmenuItems
FileInputStream wordsFile = new FileInputStream(signlink.findcachedir() + "/Playlist.div");
BufferedReader br = new BufferedReader(new InputStreamReader(wordsFile));
String[] favoriteSongs = new String[15];
for (int i = 0; i < favoriteSongs.length; i++) {
favoriteSongs[i] = br.readLine();
if (favoriteSongs[i] != null) {
System.out.println(favoriteSongs[i]);
JMenuItem song = new JMenuItem(favoriteSongs[i]);
song.addActionListener(this);
favorites.add(favoriteSongs[i]);
} else {
wordsFile.close();
break;
}
}
如何为JmenuItems添加动作
答案 0 :(得分:0)
我不确定我是否理解正确但是: 你添加了动作列表器'song.addActionListener(this)'所以这意味着你在你的类中有一个来自接口的覆盖方法,你需要在那里放一些逻辑,它应该工作,即
@Override
public void actionPerformed(ActionEvent e) {
JMenuItem item = (JMenuItem) e.getSource();
String song = item.getText();
listOfSth.add(song);
}
或者您可以创建实现ActionListner的新类并将其添加到创建的MenuItem
JMenuItem l = new JMenuItem();
l.addActionListener(new CustomActionListener());