playforjava
⑴ 求一个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]);
}
}*/
}
请采纳答案,支持我一下。