user2913066
user2913066

Reputation: 11

Listing files Jlist with jfilechooser

I need to create a mp3 player, with a play list. i am having difficult in listing at JList the files I am selecting with JFileChooser.

Can anybody help me doing this?

tks

Upvotes: 1

Views: 1589

Answers (1)

alex2410
alex2410

Reputation: 10994

Here is simple example for you, how to add selected files to JList :

public class ListExample extends JFrame {

    private DefaultListModel<String> model;

    ListExample() {
        JList<String> l = new JList<>(model = new DefaultListModel<String>());
        JButton btn = new JButton("add");
        btn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                JFileChooser fc = new JFileChooser();
                fc.setMultiSelectionEnabled(true);
                fc.showOpenDialog(new JFrame());
                File[] selectedFiles = fc.getSelectedFiles();
                for(File f : selectedFiles){
                    model.addElement(f.getName());
                }
            }
        });
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(new JScrollPane(l));
        getContentPane().add(btn,BorderLayout.SOUTH);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new ListExample();
    }
}

Also read tutorial for lists

Upvotes: 2

Related Questions