當前位置:首頁 » 編程語言 » playforjava

playforjava

發布時間: 2023-04-29 07:37:08

⑴ 求一個java游戲代碼!!!急!!!

俄羅斯方侍告塊——java源代碼提供
import java.awt.*;
import java.awt.event.*;
//俄羅斯方塊類
public class ERS_Block extends Frame{
public static boolean isPlay=false;
public static int level=1,score=0;
public static TextField scoreField,levelField;

public static MyTimer timer;
GameCanvas gameScr;

public static void main(String[] argus){
ERS_Block ers = new ERS_Block("俄羅斯方塊游戲 V1.0 Author:Vincent");
WindowListener win_listener = new WinListener();
ers.addWindowListener(win_listener);
}

//俄羅斯方塊類的構造方法
ERS_Block(String title){
super(title);

setSize(600,480);
setLayout(new GridLayout(1,2));

gameScr = new GameCanvas();
gameScr.addKeyListener(gameScr);

timer = new MyTimer(gameScr);
timer.setDaemon(true);
timer.start();
timer.suspend();

add(gameScr);

Panel rightScr = new Panel();
rightScr.setLayout(new GridLayout(2,1,0,30));
rightScr.setSize(120,500);
add(rightScr);

//右邊信息窗體的布局
MyPanel infoScr = new MyPanel();
infoScr.setLayout(new GridLayout(4,1,0,5));
infoScr.setSize(120,300);
rightScr.add(infoScr);

/和物/定義標簽和初始值
Label scorep = new Label("分數:",Label.LEFT);
Label levelp = new Label("級數:",Label.LEFT);
scoreField = new TextField(8);
levelField = new TextField(8);
scoreField.setEditable(false);
levelField.setEditable(false);
infoScr.add(scorep);
infoScr.add(scoreField);
infoScr.add(levelp);
infoScr.add(levelField);
scorep.setSize(new Dimension(20,60));
scoreField.setSize(new Dimension(20,60));
levelp.setSize(new Dimension(20,60));
levelField.setSize(new Dimension(20,60));
scoreField.setText("0");
levelField.setText("1");

//右邊控制按鈕窗體的布局
MyPanel controlScr = new MyPanel();
controlScr.setLayout(new GridLayout(5,1,0,5));
rightScr.add(controlScr);

//定義按喚談液鈕play
Button play_b = new Button("開始游戲");
play_b.setSize(new Dimension(50,200));
play_b.addActionListener(new Command(Command.button_play,gameScr));

//定義按鈕Level UP
Button level_up_b = new Button("提高級數");
level_up_b.setSize(new Dimension(50,200));
level_up_b.addActionListener(new Command(Command.button_levelup,gameScr));

//定義按鈕Level Down
Button level_down_b =new Button("降低級數");
level_down_b.setSize(new Dimension(50,200));
level_down_b.addActionListener(new Command(Command.button_leveldown,gameScr));

//定義按鈕Level Pause
Button pause_b =new Button("游戲暫停");
pause_b.setSize(new Dimension(50,200));
pause_b.addActionListener(new Command(Command.button_pause,gameScr));

//定義按鈕Quit
Button quit_b = new Button("退出遊戲");
quit_b.setSize(new Dimension(50,200));
quit_b.addActionListener(new Command(Command.button_quit,gameScr));

controlScr.add(play_b);
controlScr.add(level_up_b);
controlScr.add(level_down_b);
controlScr.add(pause_b);
controlScr.add(quit_b);
setVisible(true);
gameScr.requestFocus();
}
}

//重寫MyPanel類,使Panel的四周留空間
class MyPanel extends Panel{
public Insets getInsets(){
return new Insets(30,50,30,50);
}
}

//游戲畫布類
class GameCanvas extends Canvas implements KeyListener{
final int unitSize = 30; //小方塊邊長
int rowNum; //正方格的行數
int columnNum; //正方格的列數
int maxAllowRowNum; //允許有多少行未削
int blockInitRow; //新出現塊的起始行坐標
int blockInitCol; //新出現塊的起始列坐標
int [][] scrArr; //屏幕數組
Block b; //對方快的引用

//畫布類的構造方法
GameCanvas(){
rowNum = 15;
columnNum = 10;
maxAllowRowNum = rowNum - 2;
b = new Block(this);
blockInitRow = rowNum - 1;
blockInitCol = columnNum/2 - 2;
scrArr = new int [32][32];
}

//初始化屏幕,並將屏幕數組清零的方法
void initScr(){
for(int i=0;i<rowNum;i++)
for (int j=0; j<columnNum;j++)
scrArr[j]=0;
b.reset();
repaint();
}

//重新刷新畫布方法
public void paint(Graphics g){
for(int i = 0; i < rowNum; i++)
for(int j = 0; j < columnNum; j++)
drawUnit(i,j,scrArr[j]);
}

//畫方塊的方法
public void drawUnit(int row,int col,int type){
scrArr[row][col] = type;
Graphics g = getGraphics();
tch(type){ //表示畫方快的方法
case 0: g.setColor(Color.black);break; //以背景為顏色畫
case 1: g.setColor(Color.blue);break; //畫正在下落的方塊
case 2: g.setColor(Color.magenta);break; //畫已經落下的方法
}
g.fill3DRect(col*unitSize,getSize().height-(row+1)*unitSize,unitSize,unitSize,true);
g.dispose();
}

public Block getBlock(){
return b; //返回block實例的引用
}

//返回屏幕數組中(row,col)位置的屬性值
public int getScrArrXY(int row,int col){
if (row < 0 || row >= rowNum || col < 0 || col >= columnNum)
return(-1);
else
return(scrArr[row][col]);
}

//返回新塊的初始行坐標方法
public int getInitRow(){
return(blockInitRow); //返回新塊的初始行坐標
}

//返回新塊的初始列坐標方法
public int getInitCol(){
return(blockInitCol); //返回新塊的初始列坐標
}

//滿行刪除方法
void deleteFullLine(){
int full_line_num = 0;
int k = 0;
for (int i=0;i<rowNum;i++){
boolean isfull = true;

L1:for(int j=0;j<columnNum;j++)
if(scrArr[j] == 0){
k++;
isfull = false;
break L1;
}
if(isfull) full_line_num++;
if(k!=0 && k-1!=i && !isfull)
for(int j = 0; j < columnNum; j++){
if (scrArr[j] == 0)
drawUnit(k-1,j,0);
else
drawUnit(k-1,j,2);
scrArr[k-1][j] = scrArr[j];
}
}
for(int i = k-1 ;i < rowNum; i++){
for(int j = 0; j < columnNum; j++){
drawUnit(i,j,0);
scrArr[j]=0;
}
}
ERS_Block.score += full_line_num;
ERS_Block.scoreField.setText(""+ERS_Block.score);
}

//判斷游戲是否結束方法
boolean isGameEnd(){
for (int col = 0 ; col <columnNum; col ++){
if(scrArr[maxAllowRowNum][col] !=0)
return true;
}
return false;
}

public void keyTyped(KeyEvent e){
}

public void keyReleased(KeyEvent e){
}

//處理鍵盤輸入的方法
public void keyPressed(KeyEvent e){
if(!ERS_Block.isPlay)
return;
tch(e.getKeyCode()){
case KeyEvent.VK_DOWN:b.fallDown();break;
case KeyEvent.VK_LEFT:b.leftMove();break;
case KeyEvent.VK_RIGHT:b.rightMove();break;
case KeyEvent.VK_SPACE:b.leftTurn();break;
}
}
}

//處理控制類
class Command implements ActionListener{
static final int button_play = 1; //給按鈕分配編號
static final int button_levelup = 2;
static final int button_leveldown = 3;
static final int button_quit = 4;
static final int button_pause = 5;
static boolean pause_resume = true;

int curButton; //當前按鈕
GameCanvas scr;

//控制按鈕類的構造方法
Command(int button,GameCanvas scr){
curButton = button;
this.scr=scr;
}

//按鈕執行方法
public void actionPerformed (ActionEvent e){
tch(curButton){
case button_play:if(!ERS_Block.isPlay){
scr.initScr();
ERS_Block.isPlay = true;
ERS_Block.score = 0;
ERS_Block.scoreField.setText("0");
ERS_Block.timer.resume();
}
scr.requestFocus();
break;
case button_levelup:if(ERS_Block.level < 10){
ERS_Block.level++;
ERS_Block.levelField.setText(""+ERS_Block.level);
ERS_Block.score = 0;
ERS_Block.scoreField.setText(""+ERS_Block.score);
}
scr.requestFocus();
break;
case button_leveldown:if(ERS_Block.level > 1){
ERS_Block.level--;
ERS_Block.levelField.setText(""+ERS_Block.level);
ERS_Block.score = 0;
ERS_Block.scoreField.setText(""+ERS_Block.score);
}
scr.requestFocus();
break;
case button_pause:if(pause_resume){
ERS_Block.timer.suspend();
pause_resume = false;
}else{
ERS_Block.timer.resume();
pause_resume = true;
}
scr.requestFocus();
break;
case button_quit:System.exit(0);
}
}
}

//方塊類
class Block {
static int[][] pattern = {
{0x0f00,0x4444,0x0f00,0x4444},//用十六進至表示,本行表示長條四種狀態
{0x04e0,0x0464,0x00e4,0x04c4},
{0x4620,0x6c00,0x4620,0x6c00},
{0x2640,0xc600,0x2640,0xc600},
{0x6220,0x1700,0x2230,0x0740},
{0x6440,0x0e20,0x44c0,0x8e00},
{0x0660,0x0660,0x0660,0x0660}
};
int blockType; //塊的模式號(0-6)
int turnState; //塊的翻轉狀態(0-3)
int blockState; //快的下落狀態
int row,col; //塊在畫布上的坐標
GameCanvas scr;

//塊類的構造方法
Block(GameCanvas scr){
this.scr = scr;
blockType = (int)(Math.random() * 1000)%7;
turnState = (int)(Math.random() * 1000)%4;
blockState = 1;
row = scr.getInitRow();
col = scr.getInitCol();
}

//重新初始化塊,並顯示新塊
public void reset(){
blockType = (int)(Math.random() * 1000)%7;
turnState = (int)(Math.random() * 1000)%4;
blockState = 1;
row = scr.getInitRow();
col = scr.getInitCol();
dispBlock(1);
}

//實現「塊」翻轉的方法
public void leftTurn(){
if(assertValid(blockType,(turnState + 1)%4,row,col)){
dispBlock(0);
turnState = (turnState + 1)%4;
dispBlock(1);
}
}

//實現「塊」的左移的方法
public void leftMove(){
if(assertValid(blockType,turnState,row,col-1)){
dispBlock(0);
col--;
dispBlock(1);
}
}

//實現塊的右移
public void rightMove(){
if(assertValid(blockType,turnState,row,col+1)){
dispBlock(0);
col++;
dispBlock(1);
}
}

//實現塊落下的操作的方法
public boolean fallDown(){
if(blockState == 2)
return(false);
if(assertValid(blockType,turnState,row-1,col)){
dispBlock(0);
row--;
dispBlock(1);
return(true);
}else{
blockState = 2;
dispBlock(2);
return(false);
}
}

//判斷是否正確的方法
boolean assertValid(int t,int s,int row,int col){
int k = 0x8000;
for(int i = 0; i < 4; i++){
for(int j = 0; j < 4; j++){
if((int)(pattern[t][s]&k) != 0){
int temp = scr.getScrArrXY(row-i,col+j);
if (temp<0||temp==2)
return false;
}
k = k >> 1;
}
}
return true;
}

//同步顯示的方法
public synchronized void dispBlock(int s){
int k = 0x8000;
for (int i = 0; i < 4; i++){
for(int j = 0; j < 4; j++){
if(((int)pattern[blockType][turnState]&k) != 0){
scr.drawUnit(row-i,col+j,s);
}
k=k>>1;
}
}
}
}

//定時線程
class MyTimer extends Thread{
GameCanvas scr;

public MyTimer(GameCanvas scr){
this.scr = scr;
}

public void run(){
while(true){
try{
sleep((10-ERS_Block.level + 1)*100);
}
catch(InterruptedException e){}
if(!scr.getBlock().fallDown()){
scr.deleteFullLine();
if(scr.isGameEnd()){
ERS_Block.isPlay = false;
suspend();
}else
scr.getBlock().reset();
}
}
}

class WinListener extends WindowAdapter{
public void windowClosing (WindowEvent l){
System.exit(0);
}
}

⑵ 怎麼在電腦上運行Java源程序代碼

http://hi..com/%D1%EE%5F%C1%F5/blog/item/55d15c35a8b7ca87a71e122e.html
上面的網址是java掃雷的源代碼

要運行,首先要配置環境變數(方法可參考網上)
其次找到程序所在的盤符目錄,比如java掃雷程序,放在了
E:\Java掃雷中,那麼在DOS下就要到此目錄

然後依次輸入javac *.java(編譯
java *(運行)即可

⑶ 幾個Java小游戲代碼

package rece;
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioSystem;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Rectangle;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JSlider;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.Vector;
public class Frame extends JFrame implements Runnable {
JPanel contentPane;
JPanel jPanel1 = new JPanel();
JButton jButton1 = new JButton();
JSlider jSlider1 = new JSlider();
JLabel jLabel1 = new JLabel();
JButton jButton2 = new JButton();
JLabel jLabel2 = new JLabel();
int count = 1, rapidity = 80; // count 當前進行的個數, rapidity 游標的位置
int zhengque = 0, cuowu = 0;
int rush[] = { 10 ,20 ,30 }; //游戲每關的個數 可以自由添加.列 { 10 ,20 ,30 ,40,50}
int rush_count = 0; //記錄關數
char list[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; //隨機出現的數字 可以自由添加
Vector number = new Vector();
String paian = "true";
AudioClip Musci_anjian, Music_shi, Music_chenggong;
public Frame() {
try {
setDefaultCloseOperation(EXIT_ON_CLOSE);

//-----------------聲音文件---------------------
Musci_anjian = Applet.newAudioClip(new File("sounds//anjian.wav")
.toURL());
Music_shi = Applet.newAudioClip(new File("sounds//shi.wav")
.toURL());
Music_chenggong = Applet.newAudioClip(new File(
"sounds//chenggong.wav").toURL());

//---------------------------------------
jbInit();
} catch (Exception exception) {
exception.printStackTrace();
}
}
/**
* Component initialization.
*
* @throws java.lang.Exception
*/
private void jbInit() throws Exception {
contentPane = (JPanel) getContentPane();
contentPane.setLayout(null);
setSize(new Dimension(588, 530));
setTitle("Frame Title");
jPanel1.setBorder(BorderFactory.createEtchedBorder());
jPanel1.setBounds(new Rectangle(4, 4, 573, 419));
jPanel1.setLayout(null);
jButton1.setBounds(new Rectangle(277, 442, 89, 31));
jButton1.setText("開始");
jButton1.addActionListener(new Frame1_jButton1_actionAdapter(this));
jSlider1.setBounds(new Rectangle(83, 448, 164, 21));
jSlider1.setMaximum(100);
jSlider1.setMinimum(1);
jSlider1.setValue(50);
jLabel1.setText("速度");
jLabel1.setBounds(new Rectangle(35, 451, 39, 18));
jButton2.setBounds(new Rectangle(408, 442, 89, 31));
jButton2.setText("結束");
jButton2.addActionListener(new Frame1_jButton2_actionAdapter(this));
jLabel2.setText("第一關:100個");
jLabel2.setBounds(new Rectangle(414, 473, 171, 21));
contentPane.add(jPanel1);
contentPane.add(jButton2);
contentPane.add(jButton1);
contentPane.add(jSlider1);
contentPane.add(jLabel1);
contentPane.add(jLabel2);
this.addKeyListener(new MyListener());
jButton1.addKeyListener(new MyListener());
jSlider1.addKeyListener(new MyListener());
jSlider1.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
rapidity = jSlider1.getValue();
}
});
}
public void run() {
number.clear();
zhengque = 0;
cuowu = 0;
paian = "true";
while (count <= rush[rush_count]) {
try {
Thread t = new Thread(new Tthread());
t.start();
count += 1;
Thread.sleep(1000 + (int) (Math.random() * 2000)); // 生產下組停頓時間
// 最快1快.最慢2秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
while (true) { // 等待最後一個字元消失
if (number.size() == 0) {
break;
}
}
if (zhengque == 0) { // 為了以後相除..如果全部正確或者錯誤就會出現錯誤. 所以..
zhengque = 1;
}
if (cuowu == 0) {
cuowu = 1;
}
if (paian.equals("true")) { // 判斷是否是自然結束
if (zhengque / cuowu >= 2) {
JOptionPane.showMessageDialog(null, "恭喜你過關了");
rush_count += 1; // 自動加1關
if (rush_count < rush.length) {
if (rapidity > 10) { // 當速度大於10的時候在-5提加速度.怕速度太快
rapidity -= 5; // 速度自動減10毫秒
jSlider1.setValue(rapidity); // 選擇位置
}
Thread t = new Thread(this);
t.start();
} else {
JOptionPane.showMessageDialog(null, "牛B...你通關了..");
rush_count = 0;
count = 0;
}
} else {
JOptionPane.showMessageDialog(null, "請再接再勵");
rush_count = 0;
count = 0;
}
} else {
rush_count = 0;
count = 0;
}
}
public void jButton1_actionPerformed(ActionEvent e) {
Thread t = new Thread(this);
t.start();
}
public void jButton2_actionPerformed(ActionEvent e) {
count = rush[rush_count] + 1;
paian = "flase";
}
class Tthread implements Runnable {
public void run() {
boolean fo = true;
int Y = 0, X = 0;
JLabel show = new JLabel();
show.setFont(new java.awt.Font("宋體", Font.PLAIN, 33));
jPanel1.add(show);
X = 10 + (int) (Math.random() * 400);
String parameter = list[(int) (Math.random() * list.length)] + "";
Bean bean = new Bean();
bean.setParameter(parameter);
bean.setShow(show);
number.add(bean);
show.setText(parameter);
while (fo) {
// ---------------------數字下移--------------------
show.setBounds(new Rectangle(X, Y += 2, 33, 33));
try {
Thread.sleep(rapidity);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (Y >= 419) {
fo = false;
for (int i = number.size() - 1; i >= 0; i--) {
Bean bn = ((Bean) number.get(i));
if (parameter.equalsIgnoreCase(bn.getParameter())) {
cuowu += 1;
jLabel2.setText("正確:" + zhengque + "個,錯誤:" + cuowu
+ "個");
number.removeElementAt(i);
Music_shi.play();
break;
}
}
}
}
}
}
class MyListener extends KeyAdapter {
public void keyPressed(KeyEvent e) {
String uu = e.getKeyChar() + "";
for (int i = 0; i < number.size(); i++) {
Bean bean = ((Bean) number.get(i));
if (uu.equalsIgnoreCase(bean.getParameter())) {
zhengque += 1;
number.removeElementAt(i);
bean.getShow().setVisible(false);
jLabel2.setText("正確:" + zhengque + "個,錯誤:" + cuowu + "個");
Music_chenggong.play();
break;
}
}
Musci_anjian.play();
}
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception exception) {
exception.printStackTrace();
}
Frame frame = new Frame();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = frame.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
frame.setLocation((screenSize.width - frameSize.width) / 2,
(screenSize.height - frameSize.height) / 2);
frame.setVisible(true);
}
}
class Frame1_jButton2_actionAdapter implements ActionListener {
private Frame adaptee;
Frame1_jButton2_actionAdapter(Frame adaptee) {
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e) {
adaptee.jButton2_actionPerformed(e);
}
}
class Frame1_jButton1_actionAdapter implements ActionListener {
private Frame adaptee;
Frame1_jButton1_actionAdapter(Frame adaptee) {
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e) {
adaptee.jButton1_actionPerformed(e);
}
}
class Bean {
String parameter = null;
JLabel show = null;
public JLabel getShow() {
return show;
}
public void setShow(JLabel show) {
this.show = show;
}
public String getParameter() {
return parameter;
}
public void setParameter(String parameter) {
this.parameter = parameter;
}
}
我只有一個打字母小游戲

⑷ 如何用java做一個音樂播放器

<object id="player" height="300" width="300" classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6">
<param NAME="AutoStart" VALUE="-1">
<!--是否自動播放-->
<param NAME="Balance" VALUE="0">
<!--調整左右聲道平衡,同上面舊播放器代碼-->
<param name="enabled" value="-1">
<!--播放器是否可人為控制-->
<param NAME="EnableContextMenu" VALUE="-1">
<!--是否啟用上下文菜單-->
<param NAME="url" value="song/onceLoveYou.mp3">
<!--播放的文件地址-->
<param NAME="PlayCount" VALUE="3">
<!--播放次數控制,為整數-->
<param name="rate" value="1">
<!--播放速率控制,1為正常,允許小數,1.0-2.0-->
<param name="currentPosition" value="0">
<!--控制項設置:當前位置-->
<param name="currentMarker" value="0">
<!--控制項設置:當前標記-->
<param name="defaultFrame" value="">
<!--顯示默認框架-->
<param name="invokeURLs" value="0">
<!--腳本命令設置:是否調用URL-->
<param name="baseURL" value="">
<!--腳本命令設置:被調用的URL-->
<param name="stretchToFit" value="0">
<!--是否按比例伸展-->
<param name="volume" value="50">
<!--默認聲音大小0%-100%,50則為50%-->
<param name="mute" value="0">
<!--是否靜音-->
<param name="uiMode" value="mini">
<!--播放器顯示模式:Full顯示全部;mini最簡化;None不顯示播放控制,只顯示視頻窗口;invisible全部不顯示-->
<param name="windowlessVideo" value="0">
<!--如果是0可以允許全屏,否則只能在窗口中查看-->
<param name="fullScreen" value="0">
<!--開始播放是否自動全屏-->
<param name="enableErrorDialogs" value="-1">
<!--是否啟用錯誤提示報告-->
<param name="SAMIStyle" value>
<!--SAMI樣式-->
<param name="SAMILang" value>
<!--SAMI語言-->
<param name="SAMIFilename" value>
<!--字幕ID-->
</object>
希望對你有所幫助

⑸ java 循環播放音樂

在調用play()的後面,再次打開聲音、再調用play()

⑹ 用JAVA實現五子棋悔棋代碼

具體嘛.我覺得可以讓一個線程來做這個東西,單獨用一個線程式控制制!

⑺ 求Java編寫的視頻播放器程序

不全~代碼發不了了~,剩下的是播放器的關閉以及播放格式的支持與否,不麻煩的自己寫吧
MediaPlayer.java
----------------------------------------------------------------------------
//程序主文件
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.media.*;
import java.io.*;
import java.util.*;//為了導入Vector
//import com.sun.java.swing.plaf.windows.*;

public class MediaPlayer extends JFrame implements ActionListener,Runnable
{
private JMenuBar bar;//菜單條
private JMenu fileMenu,choiceMenu,aboutMenu;
private JMenuItem openItem,openDirItem,closeItem,about,infor;
private JCheckBoxMenuItem onTop;
private boolean top=false,loop;//設定窗口是否在最前面
private Player player;//Play是個實現Controller的介面
private File file,listFile;//利用File類結合JFileChooser進行文件打開操作,後則與list.ini有關
private Container c;
//private UIManager.LookAndFeelInfo[] look;
private String title,listIniAddress;//標題
private FileDialog fd;
private JPanel panel,panelSouth;
private Icon icon; //開始進入的時候要顯示的圖標,它為抽象類,不能自己創建
private JLabel label,listB;//用來顯示圖標

private JList list;//播放清單
private JScrollPane scroll;//使播放清單具有滾動功能
private ListValues listWriteFile;//用於向文件中讀取對象
private ObjectInputStream input;//對象輸入流
private ObjectOutputStream output;//對象輸出流

private JPopupMenu popupMenu;//滑鼠右鍵彈出菜單
private JMenuItem del,delAll,reName; //彈出菜單顯示的菜單項,包括刪除,全部刪除和重命名

private Vector fileName,dirName,numList;
private String files,dir;
private int index;//曲目指針
private Properties prop;//獲得系統屬性
private int indexForDel;//標志要刪除的列表項目的索引
private ButtonGroup buttonGroup;//控制按鈕組
private JRadioButtonMenuItem[] buttonValues;
private String[] content={"隨機播放","順序播放","單曲循環"};

private DialogDemo dialog1;
//private JDialogTest dialog2;//用於顯示播放清單

MediaPlayer()//構造函數
{
super("java音頻播放器1.1版");//窗口標題

c=getContentPane();
c.setLayout(new BorderLayout());
//c.setBackground(new Color(40,40,95));

fileName=new Vector(1);
dirName=new Vector(1);
numList=new Vector(1);//構造三個容器用於支持播放清單
//vectorToString=new String[];
//prop=new Properties(System.getProperties());
//listIniAddress=prop.getProperty("user.dir")+"\\list.ini";
//listFile=new File(listIniAddress);//本來這些代碼用來取的系統屬性,後來
//發現根本就不用這么麻煩
listFile=new File("list.ini");//直接存於此目錄
Thread readToList=new Thread(this);//注意編線程程序的時候要注意運行的時候含有的變數億定義或者初始化,
//這就要求線程要等上述所說的情況下再運行,否則很容易發生錯誤或則異常

list=new JList();
list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
list.setSelectionForeground(new Color(0,150,150));
list.setVisibleRowCount(10);
list.setFixedCellHeight(12);
list.setFixedCellWidth(250);
list.setFont(new Font("Serif",Font.PLAIN,12));
list.setBackground(new Color(40,40,95));
list.setForeground(new Color(0,128,255));
//list.setOpaque(false);
list.setToolTipText("點右鍵顯示更多功能");//創建播放清單並設置各個屬性
list.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
if (e.getClickCount() == 2) //判斷是否雙擊
{
index = list.locationToIndex(e.getPoint());//將滑鼠坐標轉化成list中的選項指針
createPlayer2();
//System.out.println("Double clicked on Item " + index);,此是測試的時候加的
}
}
/* public void mousePressed(MouseEvent e)
{
checkMenu(e);//自定義函數,判斷是否是右鍵,來決定是否顯示菜單
}*/
public void mouseReleased(MouseEvent e)
{
checkMenu(e);//與上面的一樣,判斷是否滑鼠右鍵
}

}
);
//listB=new JLabel(new ImageIcon("qingdan.gif"),SwingConstants.CENTER);
scroll=new JScrollPane(list);//用於存放播放列表
//dialog2=new JDialogTest(MediaPlayer.this,"播放清單",scroll);
//dialog2.setVisible(true);

readToList.start();//啟動先程,載入播放列表
try
{
Thread.sleep(10);
}
catch(InterruptedException e)
{
e.printStackTrace();
}

/*look=UIManager.getInstalledLookAndFeels();
try
{
UIManager.setLookAndFeel(look[2].getClassName());
SwingUtilities.updateComponentTreeUI(this);
}
catch(Exception e)
{
e.printStackTrace();
}*///與下面的代碼實現相同的功能,但執行速度要慢,原因:明顯轉了個大彎

/*try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(Exception e)
{
e.printStackTrace();
} *///此段代碼使執行速度大大降低

bar=new JMenuBar();
setJMenuBar(bar);//此兩行創建菜單欄並放到此窗口程序
//bar.setBackground(new Color(48,91,183));
fileMenu=new JMenu("文件");
bar.add(fileMenu);

choiceMenu=new JMenu("控制");
bar.add(choiceMenu);

aboutMenu=new JMenu("幫助");
bar.add(aboutMenu);

openItem =new JMenuItem("打開文件");
openDirItem =new JMenuItem("打開目錄");
closeItem =new JMenuItem("退出程序");
openItem.addActionListener(this);
openDirItem.addActionListener(this);
closeItem.addActionListener(this);
fileMenu.add(openItem);
fileMenu.add(openDirItem);
fileMenu.add(closeItem);

onTop=new JCheckBoxMenuItem("播放時位於最前面",top);
choiceMenu.add(onTop);
onTop.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
if(onTop.isSelected())
top=true;
else top=false;
setAlwaysOnTop(top);
}
}
);

choiceMenu.addSeparator();//加分割符號

buttonGroup=new ButtonGroup();
buttonValues=new JRadioButtonMenuItem[3];
for(int bt=0;bt<3;bt++)
{
buttonValues[bt]=new JRadioButtonMenuItem(content[bt]);
buttonGroup.add(buttonValues[bt]);
choiceMenu.add(buttonValues[bt]);
}
buttonValues[0].setSelected(true);
choiceMenu.addSeparator();

/*loopItem=new JCheckBoxMenuItem("是否循環");
choiceMenu.add(loopItem);
loopItem.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
loop=!loop;
}
}
);*/
infor=new JMenuItem("軟體簡介");
aboutMenu.add(infor);
infor.addActionListener(this);

about=new JMenuItem("關於作者");
about.addActionListener(this);
aboutMenu.add(about);
//菜單欄設置完畢

panel=new JPanel();
panel.setLayout(new BorderLayout());
c.add(panel,BorderLayout.CENTER);

panelSouth=new JPanel();
panelSouth.setLayout(new BorderLayout());
c.add(panelSouth,BorderLayout.SOUTH);

icon=new ImageIcon("icon\\Player.jpg");
label=new JLabel(icon);
panel.add(label);

popupMenu=new JPopupMenu();
del =new JMenuItem("刪除");//滑鼠右鍵彈出菜單對象實例化
popupMenu.add(del);
del.addActionListener(this);

delAll =new JMenuItem("全部刪除");
popupMenu.add(delAll);
delAll.addActionListener(this);
reName =new JMenuItem("重命名");
popupMenu.add(reName);
reName.addActionListener(this);

scroll=new JScrollPane(list);//用於存放播放列表
listB=new JLabel(new ImageIcon("icon\\qingdan.gif"),SwingConstants.CENTER);

panelSouth.add(listB,BorderLayout.NORTH);
panelSouth.add(scroll,BorderLayout.CENTER);

dialog1=new DialogDemo(MediaPlayer.this,"軟體說明");

this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);//設定窗口關閉方式
//this.setTitle("d");編譯通過,說明可以再次設定標題
this.setLocation(400,250);//設定窗口出現的位置
//this.setSize(350,320);//窗口大小
setSize(350,330);
this.setResizable(false);//設置播放器不能隨便調大小
this.setVisible(true);//此句不可少,否則窗口會不顯示

}

public void actionPerformed(ActionEvent e)
{
if(e.getSource()==openItem)//getSource()判斷發生時間的組鍵
{
//System.out.println("d");測試用
openFile();
//createPlayer();
//setTitle(title);

}
if(e.getSource()==openDirItem)//打開目錄
{
openDir();
}
if(e.getSource()==closeItem)//推出播放器
{
exity_n();
//System.exit(0);
}
if(e.getSource()==about)
{
JOptionPane.showMessageDialog(this,"此簡易播放器由計科0302\n"
+"harly\n "+" 完成 ",
"參與者",
JOptionPane.INFORMATION_MESSAGE);
}
if(e.getSource()==del)
{
//index
//delPaintList(index);
fileName.removeElementAt(indexForDel);
dirName.removeElementAt(indexForDel);
numList.removeAllElements();//從三個容器裡面移除此項
Enumeration enumFile=fileName.elements();
while(enumFile.hasMoreElements())
{
numList.addElement((numList.size()+1)+"."+enumFile.nextElement());
//numList添加元素,顯示播放里表中
}
//list.setListData(fileName);
list.setListData(numList);
if(index<indexForDel)
list.setSelectedValue(numList.elementAt(index),true);
else
{
if(index==indexForDel);
else
if(index!=0)
list.setSelectedValue(numList.elementAt(index-1),true);
}

//list.setSelectedIndex(index);
}

if(e.getSource()==delAll)//全部刪除
{
fileName.removeAllElements();
dirName.removeAllElements();
numList.removeAllElements();
list.setListData(numList);
}

if(e.getSource()==reName)//重命名
{
String name;//=JOptionPane.showInputDialog(this,"請輸入新的名字");
try
{
name=reNames();
fileName.setElementAt(name,indexForDel);
numList.setElementAt((indexForDel+1)+"."+name,indexForDel);
}
catch(ReName e2)//自定義的異常
{
}

}
if(e.getSource()==infor)
{
dialog1.setVisible(true);
}
}

public static void main(String[] args)
{
final MediaPlayer mp=new MediaPlayer();
mp.setIconImage(new ImageIcon("icon\\mPlayer.jpg").getImage());//改變默認圖標
mp.addWindowListener(new WindowAdapter()//注冊窗口事件
{
public void windowClosing(WindowEvent e)
{
//System.exit(0);
mp.exity_n();
}
}

);
System.out.println("注意:更新文件列表後,請先正常關閉播放器"
+"\n然後再關閉此DOS窗口,否則導致播放列表不能保存!!");
}

private void openFile()//為了界面原因,此代碼重寫,估計兼容性不好了
{
/*JFileChooser fileChooser=new JFileChooser();//文件選擇器
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);//可以選擇文件不能目錄
int result=fileChooser.showOpenDialog(this);//創建文件打開對話框,並設定此程序為父窗口監控*/

/*通過result的值來判斷文件是否打開成功
*JFileChooser類有很多靜態成員變數
**/
/*if(result==JFileChooser.CANCEL_OPTION)
{
file=null;//file已經在類中定義,如果選擇取消,file指向為空
}
else
{
file=fileChooser.getSelectedFile();//獲得文件對象
title=file.getAbsolutePath();//取得文件的絕對路徑並且賦給title設定標題
}*/
//if(fd==null)
//{
//String filename="java音頻播放器";
fd = new FileDialog(MediaPlayer.this);
//Filters fl=new Filters();
//fd.setFilenameFilter(fl);

fd.setVisible(true);
if (fd.getFile() != null)
{
title = fd.getDirectory() + fd.getFile();//原因請見同目錄下的FileDialogDemo.java文件
files=fd.getFile();
//dir =fd.getDirectory();
file=new File(title);
createPlayer();

}
//title=filename;
//fd=null;//缺少此句如果第一次打開文件的時候取消操作的時候第二次也不能打開文件了
//}
}
private void openDir()
{
JFileChooser fileChooser=new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result=fileChooser.showOpenDialog(MediaPlayer.this);
if(result==JFileChooser.CANCEL_OPTION)
return;
file=fileChooser.getSelectedFile();
if(file==null||file.getName().equals(""))
JOptionPane.showMessageDialog(this,"錯誤的路徑",
"出錯了",JOptionPane.ERROR_MESSAGE);
String[] sFiles=file.list();
for(int i=0;i<sFiles.length;i++)
{
fileName.addElement(sFiles[i]);
numList.addElement((numList.size()+1)+"."+sFiles[i]);
dirName.addElement(file.getAbsolutePath()+"\\"+sFiles[i]);
}
list.setListData(numList);

/*fd=new FileDialog(MediaPlayer.this);
fd.setVisible(true);
if(fd.getDirectory()!=null)
{
File fileDir=new File(fd.getDirectory());
String[] ss=fileDir.list();
for(int i=0;i<ss.length;i++)
{
System.out.println(ss[i]);
}
}*/
}
請採納答案,支持我一下。

熱點內容
萬科海上傳奇二期 發布:2024-11-01 14:22:52 瀏覽:59
u盤文件夾是空的 發布:2024-11-01 14:19:57 瀏覽:402
python包含字元串 發布:2024-11-01 14:19:17 瀏覽:479
c語言的精華 發布:2024-11-01 14:19:02 瀏覽:588
steam截圖文件夾 發布:2024-11-01 14:18:59 瀏覽:613
ipad怎麼往安卓傳照片 發布:2024-11-01 14:18:19 瀏覽:508
我的電腦沒有文件夾選項 發布:2024-11-01 14:13:55 瀏覽:546
vb創建資料庫表 發布:2024-11-01 14:11:55 瀏覽:872
sql聯合表 發布:2024-11-01 14:03:25 瀏覽:962
linux編程gcc 發布:2024-11-01 14:02:41 瀏覽:705