我正试图从数据库中获取歌曲位置并在另一首歌后播放一首歌曲,但在这里播放数据库中的最后一首歌并停止播放。我想播放第一首歌,然后是第二首歌。
public class FX_Musicplayer extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(final Stage stage) throws Exception {
final ArrayList<String> list = new ArrayList<String>();
try {
Statement stmt = null;
// connect to database radio
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/radio", "root", "");
stmt=conn.createStatement();
String sql = "SELECT location FROM Request";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
list.add(rs.getString(1));
}
} catch (SQLException e1) {
e1.printStackTrace();
}
for (int j = 0; j < 3; j++) {
final Group root = new Group();
String item = list.get(j);
System.out.println(item);
Media media = new Media(list.get(j));
final MediaPlayer player = new MediaPlayer(media);
MediaView view = new MediaView(player);
root.getChildren().add(view);
Scene scene = new Scene(root, 400, 400, Color.BLACK);
stage.setScene(scene);
stage.show();
player.play();
player.setOnEndOfMedia(new Runnable() {
@Override public void run()
{
player.stop();
return;
}
});
}
}
}
答案 0 :(得分:2)
您的代码存在逻辑问题。您尝试在循环中再次添加所有内容,而不仅仅是更改媒体。循环只会为您再次构建所有内容,最后您只需播放最后一个媒体。您需要播放第一个并完成,添加第二个,播放等等。
用这片美丽取代for循环。
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class Example extends Application {
final MediaView view = new MediaView();
Iterator<String> itr ;
@Override
public void start(Stage stage) throws Exception {
final Group root = new Group();
List<String> list = new ArrayList<String>();
itr = list.iterator();
//Plays the first file
play(itr.next());
root.getChildren().add(view);
Scene scene = new Scene(root, 400, 400, Color.BLACK);
stage.setScene(scene);
stage.show();
}
public void play(String mediaFile){
Media media = new Media(mediaFile);
MediaPlayer player = new MediaPlayer(media);
view.setMediaPlayer(player);
player.play();
player.setOnEndOfMedia(new Runnable() {
@Override
public void run() {
player.stop();
if (itr.hasNext()) {
//Plays the subsequent files
play(itr.next());
}
return;
}
});
}
public static void main(String[] args) {
launch(args);
}
}