我尝试创建一个系统,您可以单击该按钮,它可以播放五个随机的midi文件。它总是只播放第一首歌请帮忙。随机选择整数i
,但由于我不知道的原因,网址不会从sus2
更改,因此音频保持不变。
import java.net.URL;
import java.awt.event.*;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Option extends JFrame implements ActionListener{
/**
*
*/
private static final long serialVersionUID = 1L;
URL image= this.getClass().getResource("/tick.png");
URL url = this.getClass().getResource("/sus.mid");
ImageIcon img = new ImageIcon(image);
JButton testBut = new JButton(img);
JPanel pnl = new JPanel();
java.applet.AudioClip audio = JApplet.newAudioClip(url);
public Option(){
super("Swing Window");
pnl.add(testBut);
add(pnl);
setSize( 500,350);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
testBut.addActionListener(this);
}
public void actionPerformed(ActionEvent event){
if (event.getSource() == testBut) {
int i = (int) Math.ceil(Math.random() * 5);
switch(i){
case 1: url = this.getClass().getResource("/sus.mid");
case 2: url = this.getClass().getResource("/sus2.mid");
case 3: url = this.getClass().getResource("/sus3.mid");
case 4: url = this.getClass().getResource("/sus4.mid");
case 5: url = this.getClass().getResource("/sus5.mid");
System.out.println(i);
}
audio = JApplet.newAudioClip(url);
audio.stop();
audio.play();
}
}
public static void main(String[] args){
Option gui = new Option();
}
}
答案 0 :(得分:3)
你在每个案件阻止后忘记了中断指令:
case 1:
url = this.getClass().getResource("/sus.mid");
break;
case 2:
url = this.getClass().getResource("/sus2.mid");
break;
...