我想让客户端从文本文件中加载玩家最喜欢的歌曲并放入每一行
全类同学都在这里:
http://pastebin.com/TeMk3Nft (因为如果我将其发布在这里,代码与文本就会太多)
但是我不太确定该怎么做
p.s 我不太确定循环应该迭代什么(第 104 行)
最佳答案
您的类(class)非常庞大,并且缺少其他类(class)的引用。不过,我已经为您整理了一个示例。我相信这会对您有所帮助。
import java.awt.EventQueue;
public class SongPlayer {
private JFrame frmSongPlayer;
private List<String> songs;
private ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JMenuItem) {
JMenuItem item = (JMenuItem) e.getSource();
// now
String url = "http://songs/" + item.getName();
System.out.println(url);
}
}
};
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SongPlayer window = new SongPlayer();
window.frmSongPlayer.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public SongPlayer() {
try {
songs = FileUtils.readLines(new File(SongPlayer.class.getResource("/PlayList.txt").getPath()));
} catch (IOException e) {
e.printStackTrace();
}
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmSongPlayer = new JFrame();
frmSongPlayer.setTitle("Song player");
frmSongPlayer.setBounds(100, 100, 450, 300);
frmSongPlayer.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmSongPlayer.getContentPane().setLayout(null);
JMenuBar songBar = new JMenuBar();
songBar.setBounds(10, 11, 101, 23);
frmSongPlayer.getContentPane().add(songBar);
JMenu song = new JMenu("Songs");
songBar.add(song);
for (String mp3song : songs) {
JMenuItem mntmNewMenuItem = new JMenuItem(mp3song);
mntmNewMenuItem.setName(mp3song);
mntmNewMenuItem.addActionListener(listener);
song.add(mntmNewMenuItem);
}
}
}
上面的类(class)将打开带有歌曲菜单的 Swing UI
,并且从 Playlist.txt
文件中选择项目。当您单击歌曲时,它会生成适当的 url。
关于java - 通过读取文本文件来添加 JButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19244789/