Toolkit(画像と音楽)

/*************************/
/* 画像と音楽            */
/*   coded by Y.Suganuma */
/*************************/
import java.io.*; 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.sound.midi.*;
import javax.sound.sampled.*;

public class Test {
	public static void main (String[] args)
	{
		Win win = new Win("描画の基本");
	}
}

class Win extends JFrame
{
	/******************/
	/* コンストラクタ */
	/******************/
	Win(String name)
	{
					// JFrameクラスのコンストラクタ(Windowのタイトルを引き渡す)
		super(name);
					// Windowの大きさ
		setSize(240, 190);
					// Windowの位置(中央)
		Dimension d = getToolkit().getScreenSize();   // ディスプレイの大きさ
		setLocation(d.width / 2 - 120, d.height / 2 - 90);
					// 描画パネル
		DrawPanel pn = new DrawPanel(this);
		getContentPane().add(pn);   
					// ウィンドウを表示
		setVisible(true);
					// イベントアダプタ
		addWindowListener(new WinEnd());
	}

	/******************************/
	/* 上,左,下,右の余白の設定 */
	/******************************/
	public Insets getInsets()
	{
		return new Insets(50, 20, 20, 20);
	}

	/************/
	/* 終了処理 */
	/************/
	class WinEnd extends WindowAdapter
	{
		public void windowClosing(WindowEvent e) {
			System.exit(0);
		}
	}
}

/**************/
/* 描画パネル */
/**************/
class DrawPanel extends JPanel
{
	Image im;

	DrawPanel(Win dr) {
					// 背景色
		setBackground(new Color(255, 255, 255));
					// 画像の読み込みと描画
		im = dr.getToolkit().getImage("fig0.gif");
		repaint();
					// BGM の読み込みと再生
		try
		{ 
			BGMPlayer BGM = new BGMPlayer(); 
//			BGM.cp.start();    // AIFF,AIFC,WAVE 等の場合
			BGM.player.start();   // MIDI の場合
		} 
		catch (Exception e) 
		{ 
			System.out.println("***error***"); 
		} 
	}
					// 描画
	public void paintComponent(Graphics g)
	{
		super.paintComponent(g);   // 親クラスの描画
		g.drawImage(im, 20, 30, this);
	}
}

/**********************/
/* BGM の再生(MIDI) */
/**********************/
class BGMPlayer 
{ 
	Sequencer player;
	BGMPlayer() throws MidiUnavailableException, InvalidMidiDataException, IOException
	{
		player = MidiSystem.getSequencer();
		Sequence sqc  = MidiSystem.getSequence(new File("test.mid"));
		player.setSequence(sqc);
		player.setLoopCount(Sequencer.LOOP_CONTINUOUSLY);   // 無限界演奏
		player.open();
//		player.start();
//		player.stop();
//		player.close();
	}
}

/*************************************/
/* BGM の再生(AIFF,AIFC,WAVE 等) */
/*************************************/
/*
	Clip cp;
			// コンストラクタ
	BGMPlayer() throws UnsupportedAudioFileException, IOException, LineUnavailableException 
	{ 
			// AudioInputStream の取得
		AudioInputStream ais = AudioSystem.getAudioInputStream(new File("test.aif").getAbsoluteFile()); 
			// Clip の取得
		cp = AudioSystem.getClip(); 
 		cp.open(ais); 
		cp.loop(Clip.LOOP_CONTINUOUSLY); 
	} 
}
*/