Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Playlist Shuffle with Collections.shuffle(......)

  1. #1
    Junior Member
    Join Date
    Feb 2019
    Posts
    21
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Playlist Shuffle with Collections.shuffle(......)

    We got assigned to make a mediaplayer with a playlist and some extra functions, the last function that doesn't work is the shuffle one.

    I'll drop here the main. I know it's long..

    /*****************************************************************
     * Opdracht:
     * 
     * - 3 knoppen Sorteren dienen opnieuw geactiveerd te worden
     * - knop shuffle opnieuw activeren
     * - dubbel klik op een liedje in de linkse tabel --> liedje komt rechts in de playlist
     * 	
     *****************************************************************/
     
    package Main;
     
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ComponentListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.io.File;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.List;
    import java.util.Vector;
    import javax.swing.*;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.table.DefaultTableModel;
     
    import javafx.scene.media.MediaPlayer;
    import javafx.util.Duration;
    import Model.Song;
    import Model.SongLijst;
    import javafx.beans.InvalidationListener;
    import javafx.beans.Observable;
    import javafx.scene.media.Media;
     
    @SuppressWarnings("serial")
     
    public class MainApp extends JFrame {
     
    	JTable tabelLinks;
    	JTable tabelRechts;
    	JButton knopToevoegen;
    	JButton knopVerwijderen;
    	JButton knopShuffle;
    	JButton knopSorterenOpTitel;
    	JButton knopSorterenOpArtist;
    	JButton knopSorterenOpAlbum;
    	JButton knopKiesMuziekBasismap;
    	JButton knopPlay;
    	JButton knopPauze;
    	JFileChooser fileChooser;
    	JLabel label_volume;
    	JSlider slider_volume;
    	JLabel label_navigatie;
    	JSlider slider_navigatie;
    	JLabel label_tijd;
     
    	File dir;
    	SongLijst sl;
    	MediaPlayer m;
    	double volume = 0.5;
    	boolean paused = false;
     
    	public MainApp() {
    		new javafx.embed.swing.JFXPanel(); // nodige initialisatie om de javaFX mediaplayer te kunnen gebruiken in Swing
    		sl = new SongLijst();
    		dir = new File("music");
    		sl.init(dir);
    		sl.sorteerOpArtist();
    		sl.sorteerOpAlbum();
    		sl.sorteerOpTitel();
     
    		// maak het modelLinks
    		DefaultTableModel modelLinks = new DefaultTableModel() {
    			// maak niet editeerbaar
    			public boolean isCellEditable(int row, int column) {
    				return false;
    			}
    		};
    		modelLinks.addColumn("Titel");
    		modelLinks.addColumn("Artist");
    		modelLinks.addColumn("Album");
    		modelLinks.addColumn("File");
     
    		// maak het modelRechts
    		DefaultTableModel modelRechts = new DefaultTableModel() {
    			// maak niet editeerbaar
    			public boolean isCellEditable(int row, int column) {
    				return false;
    			}
    		};
     
    		modelRechts.addColumn("Titel");
    		modelRechts.addColumn("Artist");
    		modelRechts.addColumn("Album");
    		modelRechts.addColumn("File");
     
    		// vul gegevens in voor modelLinks
    		for (Song s : sl.getLijst()) {
    			modelLinks.addRow(new Object[] { s.getTitel(), s.getArtist(), s.getAlbum(), s.getFile() });
    		}
     
    		// maak tabelLinks met schuifbalk
    		tabelLinks = new JTable(modelLinks);
    		tabelLinks.setColumnSelectionAllowed(false);
    		tabelLinks.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    		tabelLinks.getColumnModel().getColumn(0).setPreferredWidth(188);
    		tabelLinks.getColumnModel().getColumn(1).setPreferredWidth(188);
    		tabelLinks.getColumnModel().getColumn(2).setPreferredWidth(188);
    		tabelLinks.removeColumn(tabelLinks.getColumnModel().getColumn(3));
    		JScrollPane scrollTabelLinks = new JScrollPane(tabelLinks);
    		scrollTabelLinks.setPreferredSize(new Dimension(570, 700));
     
    		// maak tabelRechts met schuifbalk
    		tabelRechts = new JTable(modelRechts);
    		tabelRechts.setColumnSelectionAllowed(false);
    		tabelRechts.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    		tabelRechts.getColumnModel().getColumn(0).setPreferredWidth(188);
    		tabelRechts.getColumnModel().getColumn(1).setPreferredWidth(188);
    		tabelRechts.getColumnModel().getColumn(2).setPreferredWidth(188);
    		tabelRechts.removeColumn(tabelRechts.getColumnModel().getColumn(3));
    		JScrollPane scrollTabelRechts = new JScrollPane(tabelRechts);
    		scrollTabelRechts.setPreferredSize(new Dimension(570, 700));
     
    		// hoofdpanel
    		JPanel panelHoofd = new JPanel(new BorderLayout());
     
    		// panel voor de knoppen bovenaan
    		JPanel panelBoven = new JPanel();
    		panelBoven.setLayout(new BoxLayout(panelBoven, BoxLayout.LINE_AXIS));
    		knopSorterenOpTitel = new JButton("Sorteren op Titel       ");
    		knopSorterenOpArtist = new JButton("Sorteren op Artist       ");
    		knopSorterenOpAlbum = new JButton("Sorteren op Album            ");
    		knopKiesMuziekBasismap = new JButton("Kies bibliotheek");
    		knopPlay = new JButton(">");
    		knopPauze = new JButton("||");
    		slider_volume = new JSlider(JSlider.HORIZONTAL, 0, 100, (int) (volume * 100)); // horizontaal, min, max,
    																						// startpositie
    		slider_navigatie = new JSlider(JSlider.HORIZONTAL, 0, 100, 0); // vertikaal, min, max, startpositie
    		label_volume = new JLabel("Volume :");
    		label_navigatie = new JLabel("Navigatie :");
    		label_tijd = new JLabel("");
    		panelBoven.add(knopSorterenOpTitel);
    		panelBoven.add(knopSorterenOpArtist);
    		panelBoven.add(knopSorterenOpAlbum);
    		panelBoven.add(knopKiesMuziekBasismap);
    		panelBoven.add(knopPlay);
    		panelBoven.add(knopPauze);
    		panelBoven.add(label_volume);
    		panelBoven.add(slider_volume);
    		panelBoven.add(label_navigatie);
    		panelBoven.add(slider_navigatie);
    		panelBoven.add(label_tijd);
     
    		// panel voor de knoppen centraal
    		JPanel panelCentraal = new JPanel();
    		panelCentraal.setLayout(new BoxLayout(panelCentraal, BoxLayout.Y_AXIS));
    		knopToevoegen = new JButton("Toevoegen >>");
    		knopVerwijderen = new JButton("<< Verwijderen");
    		knopShuffle = new JButton("Shuffle");
    		panelCentraal.add(knopToevoegen);
    		panelCentraal.add(knopVerwijderen);
    		panelCentraal.add(knopShuffle);
    		knopToevoegen.setEnabled(false);
    		knopVerwijderen.setEnabled(false);
     
    		// knopToevoegen enable zetten zolang er een selectie links is
    		tabelLinks.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
    			public void valueChanged(ListSelectionEvent e) {
    				int count = tabelLinks.getSelectedRowCount();
    				knopToevoegen.setEnabled(count > 0);
    			}
    		});
     
    		// knopVerwijderen enable zetten zolang er een selectie rechts is
    		tabelRechts.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
    			public void valueChanged(ListSelectionEvent e) {
    				int count = tabelRechts.getSelectedRowCount();
    				knopVerwijderen.setEnabled(count > 0);
    			}
    		});
     
    		// event-handler voor knopToevoegen
    		knopToevoegen.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				DefaultTableModel fromModel = (DefaultTableModel) tabelLinks.getModel();
    				DefaultTableModel toModel = (DefaultTableModel) tabelRechts.getModel();
    				for (int index : tabelLinks.getSelectedRows()) {
    					Vector rowValue = (Vector) fromModel.getDataVector().get(index);
    					toModel.addRow(rowValue);
    				}
    				tabelLinks.clearSelection();
    			}
    		});
     
    		// event-handler voor knopVerwijderen
    		knopVerwijderen.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				DefaultTableModel fromModel = (DefaultTableModel) tabelRechts.getModel();
    				int selectedRow = -1;
    				while ((selectedRow = tabelRechts.getSelectedRow()) != -1) {
    					fromModel.removeRow(selectedRow);
    				}
    			}
    		});
     
    		// event-handler voor knopSorterenOpTitel
    		knopSorterenOpTitel.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				sl.sorteerOpTitel();
    				DefaultTableModel model = (DefaultTableModel) tabelLinks.getModel();
    				model.setNumRows(0);
    				for (Song s : sl.getLijst()) {
    					modelLinks.addRow(new Object[] { s.getTitel(), s.getArtist(), s.getAlbum(), s.getFile() });
     
    				}
    			}
    		});
     
    		// event-handler voor knopSorterenOpArtist
    		knopSorterenOpArtist.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				sl.sorteerOpArtist();
    				DefaultTableModel model = (DefaultTableModel) tabelLinks.getModel();
    				model.setNumRows(0);
    				for (Song s : sl.getLijst()) {
    					modelLinks.addRow(new Object[] { s.getTitel(), s.getArtist(), s.getAlbum(), s.getFile() });
     
    				}
    			}
    		});
     
    		// event-handler voor knopSorterenOpAlbum
    		knopSorterenOpAlbum.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				sl.sorteerOpAlbum();
    				DefaultTableModel model = (DefaultTableModel) tabelLinks.getModel();
    				model.setNumRows(0);
    				for (Song s : sl.getLijst()) {
    					modelLinks.addRow(new Object[] { s.getTitel(), s.getArtist(), s.getAlbum(), s.getFile() });
     
    				}
    			}
    		});
     
    		// event-handler voor knopKiesMuziekBasismap
    		fileChooser = new JFileChooser();
    		fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    		knopKiesMuziekBasismap.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				int returnVal = fileChooser.showOpenDialog(null);
    				if (returnVal == JFileChooser.APPROVE_OPTION) {
    					JOptionPane.showMessageDialog(null, "duurt 3 seconden per 10 000 te onderzoeken bestanden",
    							"Opbouwen muziekbibliotheek", JOptionPane.PLAIN_MESSAGE);
    					dir = fileChooser.getSelectedFile();
    					sl.init(dir);
    					sl.sorteerOpArtist();
    					DefaultTableModel model = (DefaultTableModel) tabelLinks.getModel();
    					model.setNumRows(0);
    					for (Song s : sl.getLijst()) {
    						model.addRow(new Object[] { s.getTitel(), s.getArtist(), s.getAlbum(), s.getFile() });
    					}
    				}
    			}
    		});
     
    		// event-handler voor knopPlay
    		knopPlay.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				DefaultTableModel model = (DefaultTableModel) tabelRechts.getModel();
    				int selectedRow = tabelRechts.getSelectedRow();
    				if (!paused) {
    					if (selectedRow != -1) {
    						File file = (File) model.getValueAt(selectedRow, 3);
    						String uriString = file.toURI().toString();
    						if (m != null)
    							m.dispose();
    						m = new MediaPlayer(new Media(uriString));
    						slider_volume.setValue((int) (volume * 100));
    						slider_navigatie.setValue(0);
    						// event-handler om de navigatie-slider te laten schuiven
    						m.currentTimeProperty().addListener(new InvalidationListener() {
    							public void invalidated(Observable ov) {
    								double s = m.getCurrentTime().toSeconds();
    								slider_navigatie.setValue((int) (s / m.getMedia().getDuration().toSeconds() * 100));
    								int sec = (int) s;
    								int uren = sec / 3600;
    								sec = sec % 3600;
    								int min = sec / 60;
    								sec = sec % 60;
    								label_tijd.setText((uren != 0 ? uren : "") + " " + min + " : " + sec + "            ");
    							}
    						});
    						// event-handler voor einde liedje --> start volgend liedje
    						m.setOnEndOfMedia(new Runnable() {
    							public void run() {
    								int selectedRow = tabelRechts.getSelectedRow();
    								if (selectedRow == tabelRechts.getModel().getRowCount() - 1)
    									selectedRow = 0;
    								else
    									selectedRow++;
    								tabelRechts.setRowSelectionInterval(selectedRow, selectedRow);
    								knopPlay.doClick();
    							}
    						});
    						if (m != null)
    							m.play();
    					}
    				} else if (m != null)
    					m.play();
    				paused = false;
    			}
    		});
     
    		// event-handler voor knopPauze
    		knopPauze.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				paused = true;
    				if (m != null)
    					m.pause();
    			}
    		});
     
    		// event-handler voor slider_volume
    		slider_volume.addChangeListener(new ChangeListener() {
    			public void stateChanged(ChangeEvent e) {
    				if (m != null) {
    					JSlider source = (JSlider) e.getSource();
    					volume = (double) source.getValue() / 100;
    					m.setVolume(volume);
    				}
    			}
    		});
     
    		// event-handler voor slider_navigatie
    		slider_navigatie.addChangeListener(new ChangeListener() {
    			public void stateChanged(ChangeEvent e) {
    				JSlider source = (JSlider) e.getSource();
    				if (m != null) {
    					if (source.getValueIsAdjusting())
    						m.seek(Duration.seconds(source.getValue() / 100.0 * m.getMedia().getDuration().toSeconds()));
    				}
    			}
    		});
     
    		// event-handler voor dubbel klik op liedje rechts om het af te spelen
    		tabelRechts.addMouseListener(new MouseAdapter() {
    			public void mouseClicked(MouseEvent evt) {
    				if (evt.getClickCount() == 2) {
    					paused = false;
    					knopPlay.doClick();
    				}
    			}
    		});
     
    		// event-handler voor dubbel klik op liedje links om het rechts in de playlist
    		// te krijgen
    		tabelLinks.addMouseListener(new MouseAdapter() {
    			public void mouseClicked(MouseEvent evt) {
    				if (evt.getClickCount() == 2) {
    					DefaultTableModel fromModel = (DefaultTableModel) tabelLinks.getModel();
    					DefaultTableModel toModel = (DefaultTableModel) tabelRechts.getModel();
    					for (int index : tabelLinks.getSelectedRows()) {
    						Vector rowValue = (Vector) fromModel.getDataVector().get(index);
    						toModel.addRow(rowValue);
    					}
    					tabelLinks.clearSelection();
    				}
    			}
    		});
     
    		// event-handler voor knopShuffle
    		knopShuffle.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				DefaultTableModel model = (DefaultTableModel) tabelRechts.getModel();
    				Collections.shuffle(sl.getLijst());
    				model.setNumRows(0);
    				for (Song s : sl.getLijst()) {
    					modelRechts.addRow(new Object[] { s.getTitel(), s.getArtist(), s.getAlbum(), s.getFile() });
     
    				}
    			}
    		});
     
    		// laatste initialisaties
    		panelHoofd.add(panelBoven, BorderLayout.PAGE_START);
    		panelHoofd.add(scrollTabelLinks, BorderLayout.WEST);
    		panelHoofd.add(scrollTabelRechts, BorderLayout.EAST);
    		panelHoofd.add(panelCentraal, BorderLayout.CENTER);
     
    		this.getContentPane().add(panelHoofd);
    		this.setBounds(20, 50, 1280, 800);
    		this.setVisible(true);
    		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    		this.setTitle("MediaPlayer 1.0");
    	}
     
    	public static void main(String[] args) {
    		MainApp app = new MainApp();
    	}
     
    }

    I don't know if you can see where the part is but it's from number 376-386.
    or the title is: // event-handler voor knopShuffle

    Then there are more classes but i think the other important ones are Song and SongLijst.

    package Model;
    import java.io.File;
     
    public class Song {
     
    	private String titel;
    	private String artist;
    	private String album;
    	private File file;
     
    	public Song(String titel, String uitvoerder, String album, File file) {
    		this.titel = titel;
    		this.artist = uitvoerder;
    		this.album = album;
    		this.file = file;
    	}
     
    	public String getTitel() {
    		return titel;
    	}
     
    	public void setTitel(String titel) {
    		this.titel = titel;
    	}
     
    	public String getArtist() {
    		return artist;
    	}
     
    	public void setArtist(String uitvoerder) {
    		this.artist = uitvoerder;
    	}
     
    	public String getAlbum() {
    		return album;
    	}
     
    	public void setAlbum(String album) {
    		this.album = album;
    	}
     
    	public File getFile() {
    		return file;
    	}
     
    	public void setFile(File file) {
    		this.file = file;
    	}
     
     
    }

    package Model;
    import java.io.File;
    import java.io.FileInputStream;
    import java.util.ArrayList;
    import java.util.Collections;
     
    import Comparator.ComparatorAlbum;
    import Comparator.ComparatorArtist;
    import Comparator.ComparatorTitel;
    import mp3Tools.MP3Tools;
     
    public class SongLijst {
    	private ArrayList<Song> lijst;
     
    	public SongLijst(){
    		lijst = new ArrayList<Song>();
    	}
     
    	// onderzoek de directory "dir" met al zijn subdirectories en bouw een lijst van songs op
    	public void init(File dir){
    		lijst.clear();
    		ArrayList<File> mp3Lijst = new ArrayList<File>();
    		MP3Tools.maak_mp3Lijst(dir, mp3Lijst);
    		Song song;
    		String  titel, artist, album;
    		String id3 = null;
    		for (File f : mp3Lijst) {
    			try {
    				FileInputStream file = new FileInputStream(f);
    				int lengte = (int) f.length();
    				file.skip(lengte - 128);
    				byte[] laatste128 = new byte[128];
    				file.read(laatste128);
    				id3 = new String(laatste128);
    				String tag = id3.substring(0, 3);
    				if (tag.equals("TAG")) {				
    					titel =  id3.substring(3, 32).trim();
    					artist =  id3.substring(33, 62).trim();
    					album = id3.substring(63, 91).trim(); 
    					song = new Song(titel, artist, album, f);
    					lijst.add(song);
    				} 
    				file.close();
    			} catch (Exception e) {
    				System.out.println("Error - " + e.toString());
    			}
    		}
    	}
     
    	public ArrayList<Song> getLijst(){
    		return lijst;
    	}
     
    	public void sorteerOpTitel() {
    		Collections.sort(lijst, new ComparatorTitel());
    	}
     
    	public void sorteerOpArtist() {
    		Collections.sort(lijst, new ComparatorArtist());
    	}
     
    	public void sorteerOpAlbum() {
    		Collections.sort(lijst, new ComparatorAlbum());
    	}
     
    }


    I wanne do Collections.shuffle(...) but you need a list and sl Collections.shuffle(sl) is wrong because sl isn't the list to the right, it's from the left so I don't know what list i should take to shuffle because if i select a song and put add it to the right I can't see it get in an list.? Any help? The code I got there is probably wrong so any help is appreciated.

  2. #2
    Member
    Join Date
    Sep 2018
    Location
    Virginia
    Posts
    284
    My Mood
    Cool
    Thanks
    0
    Thanked 38 Times in 36 Posts

    Default Re: Playlist Shuffle with Collections.shuffle(......)

    Try putting some print statements before and after the shuffle method to check and see if it is working.

    Regards,
    Jim

  3. The Following User Says Thank You to jim829 For This Useful Post:

    TmDee (May 15th, 2019)

Similar Threads

  1. [SOLVED] shuffle array items?
    By kassavetova in forum What's Wrong With My Code?
    Replies: 13
    Last Post: November 11th, 2013, 12:51 PM
  2. Card shuffle program
    By Grot in forum What's Wrong With My Code?
    Replies: 6
    Last Post: March 10th, 2013, 01:24 PM
  3. Please help with unwrap, deck, shuffle cards
    By pots in forum What's Wrong With My Code?
    Replies: 1
    Last Post: February 6th, 2013, 12:46 PM
  4. HashMap Shuffle Card
    By d'fitz in forum What's Wrong With My Code?
    Replies: 5
    Last Post: June 8th, 2011, 07:00 AM
  5. [SOLVED] I am trying to shuffle up an array
    By rsala004 in forum Collections and Generics
    Replies: 3
    Last Post: July 18th, 2009, 03:31 PM

Tags for this Thread