通过从文本文件中读取来添加JButton

时间:2013-10-08 10:07:36

标签: java swing text jbutton bufferedreader

我想让客户端从文本文件中加载播放器最喜欢的歌曲并放入每一行

全班都在这里:

http://pastebin.com/TeMk3Nft(因为如果我在这里发布它,那么代码与文本相比就太多了)

但我不确定该怎么做

p.s我不确定循环应该迭代什么(第104行)

1 个答案:

答案 0 :(得分:1)

你的课很庞大,缺少其他课程参考资料。但是,我已经为你准备了一个例子。我相信这会对你有帮助。

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);
        }

    }
}

上面的课程将会打开Swing UI的歌曲菜单,并从Playlist.txt文件中选择项目。当您点击歌曲时,它会生成相应的网址。