?? chap12-9.txt
字號:
// 程序12-9
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class playAudio extends JApplet {
AudioClip sound1, sound2, currentSound;
JButton playSound, loopSound, stopSound;
JComboBox choose;
public void init( ){ // 初始化各對象
Container container = getContentPane( ); // 獲取內容格
container.setLayout( new FlowLayout( ) ); // 設置布局
String choices[ ] = { "Welcome", "Hi" }; // 下拉列表的選項
choose = new JComboBox( choices ); // 定義一個下拉列表
choose.addItemListener( // 定義一個匿名類,實現選擇監聽
new ItemListener( ) {
// 若重新選擇聲音文件,將停止當前播放,啟動新選的聲音剪輯
public void itemStateChanged( ItemEvent e ) {
currentSound.stop( ); // 停止當前播放的聲音剪輯
// 確定新選的聲音剪輯
currentSound = choose.getSelectedIndex( ) == 0 ? sound1 : sound2;
}
}
);
container.add( choose ); // 將組件choose加入到容器中
// 定義按鈕對象,并設置事件監聽者
ButtonHandler handler = new ButtonHandler( );
playSound = new JButton( "Play" );
playSound.addActionListener( handler );
container.add( playSound );
loopSound = new JButton( "Loop" );
loopSound.addActionListener( handler );
container.add( loopSound );
stopSound = new JButton( "Stop" );
stopSound.addActionListener( handler );
container.add( stopSound );
// 載入聲音剪輯,并對currentSound初始化
sound1 = getAudioClip( getDocumentBase( ), "welcome.wav" );
sound2 = getAudioClip( getDocumentBase( ), "hi.au" );
currentSound = sound1;
}
// 當用戶單擊stop按鈕時,終止播放聲音剪輯
public void stop( ) {
currentSound.stop( );
}
// 定義一個內部類,處理按鈕事件
private class ButtonHandler implements ActionListener {
// 處理 play,loop和stop 按鈕事件
public void actionPerformed( ActionEvent actionEvent ){
if ( actionEvent.getSource( ) == playSound )
currentSound.play( );
else if ( actionEvent.getSource( ) == loopSound )
currentSound.loop( );
else if ( actionEvent.getSource( ) == stopSound )
currentSound.stop( );
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -