java如何运行一个在播放歌曲的同时创建和更改UI的方法?
播放Mp3歌曲时,程序应反复更改背景颜色。 问题是,它会先播放歌曲,然后再创建UI。我试图将player方法的代码块嵌入flash方法,但同样的情况也发生了。如果我把它放在Ui代码块之后,程序会在创建Ui后播放歌曲
现在我的问题是:如何更改代码以同时运行这两种方法(播放歌曲和更改背景颜色)
import javazoom.jl.player.Player;
import javax.swing.*;
import java.awt.*;
import java.io.FileInputStream;
import java.util.Random;
public class MainClass {
UI ui = new UI();
public MainClass() throws InterruptedException {
String mp3Url = "url of MP3-File";
int sleepMillisec = 100;
int i = 600;
ui.player(mp3Url);
ui.flash(i, sleepMillisec);
}
public static void main(String[] args) throws InterruptedException {
new MainClass();
}
public class UI {
JFrame window;
Container con;
public void player(String mp3Url) {
try {
FileInputStream fis = new FileInputStream(mp3Url);
Player playMP3 = new Player(fis);
playMP3.play();
} catch (Exception e) {
System.out.println(e);
}
}
public void flash(int i, int sleepMillisec) throws InterruptedException {
window = new JFrame();
window.setSize(800, 550);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().setBackground(Color.black);
window.setLayout(null);
con = window.getContentPane();
for (int k = 0; k < i; k++) {
Thread.sleep(sleepMillisec);
Random diceColor = new Random();
int randomColorBg = diceColor.nextInt(2);
switch (randomColorBg) {
case 0:
window.getContentPane().setBackground(Color.yellow);
break;
case 1:
window.getContentPane().setBackground(Color.black);
break;
}
window.setVisible(true);
con.setVisible(true);
}
}
}
}
# 1 楼答案
UI线程是阻塞线程。你需要开始另一个线程来播放你的歌曲
我更新了你的代码: