用JAVA编写一个小应用程序

用JAVA编写一个小应用程序,第1张

单人版五子棋,自己写的。

------------------------------------------

import javaawt;

import javaawtevent;

import javaxswing;

class mypanel extends Panel implements MouseListener

{

int chess[][] = new int[11][11];

boolean Is_Black_True;

mypanel()

{

Is_Black_True = true;

for(int i = 0;i < 11;i++)

{

for(int j = 0;j < 11;j++)

{

chess[i][j] = 0;

}

}

addMouseListener(this);

setBackground(ColorBLUE);

setBounds(0, 0, 360, 360);

setVisible(true);

}

public void mousePressed(MouseEvent e)

{

int x = egetX();

int y = egetY();

if(x < 25 || x > 330 + 25 ||y < 25 || y > 330+25)

{

return;

}

if(chess[x/30-1][y/30-1] != 0)

{

return;

}

if(Is_Black_True == true)

{

chess[x/30-1][y/30-1] = 1;

Is_Black_True = false;

repaint();

Justisewiner();

return;

}

if(Is_Black_True == false)

{

chess[x/30-1][y/30-1] = 2;

Is_Black_True = true;

repaint();

Justisewiner();

return;

}

}

void Drawline(Graphics g)

{

for(int i = 30;i <= 330;i += 30)

{

for(int j = 30;j <= 330; j+= 30)

{

gsetColor(ColorWHITE);

gdrawLine(i, j, i, 330);

}

}

for(int j = 30;j <= 330;j += 30)

{

gsetColor(ColorWHITE);

gdrawLine(30, j, 330, j);

}

}

void Drawchess(Graphics g)

{

for(int i = 0;i < 11;i++)

{

for(int j = 0;j < 11;j++)

{

if(chess[i][j] == 1)

{

gsetColor(ColorBLACK);

gfillOval((i + 1) 30 - 8, (j + 1) 30 - 8, 16, 16);

}

if(chess[i][j] == 2)

{

gsetColor(ColorWHITE);

gfillOval((i + 1) 30 - 8, (j + 1) 30 - 8, 16, 16);

}

}

}

}

void Justisewiner()

{

int black_count = 0;

int white_count = 0;

int i = 0;

for(i = 0;i < 11;i++)//横向判断

{

for(int j = 0;j < 11;j++)

{

if(chess[i][j] == 1)

{

black_count++;

if(black_count == 5)

{

JOptionPaneshowMessageDialog(this, "黑棋胜利");

Clear_Chess();

return;

}

}

else

{

black_count = 0;

}

if(chess[i][j] == 2)

{

white_count++;

if(white_count == 5)

{

JOptionPaneshowMessageDialog(this, "白棋胜利");

Clear_Chess();

return;

}

}

else

{

white_count = 0;

}

}

}

for(i = 0;i < 11;i++)//竖向判断

{

for(int j = 0;j < 11;j++)

{

if(chess[j][i] == 1)

{

black_count++;

if(black_count == 5)

{

JOptionPaneshowMessageDialog(this, "黑棋胜利");

Clear_Chess();

return;

}

}

else

{

black_count = 0;

}

if(chess[j][i] == 2)

{

white_count++;

if(white_count == 5)

{

JOptionPaneshowMessageDialog(this, "白棋胜利");

Clear_Chess();

return;

}

}

else

{

white_count = 0;

}

}

}

for(i = 0;i < 7;i++)//左向右斜判断

{

for(int j = 0;j < 7;j++)

{

for(int k = 0;k < 5;k++)

{

if(chess[i + k][j + k] == 1)

{

black_count++;

if(black_count == 5)

{

JOptionPaneshowMessageDialog(this, "黑棋胜利");

Clear_Chess();

return;

}

}

else

{

black_count = 0;

}

if(chess[i + k][j + k] == 2)

{

white_count++;

if(white_count == 5)

{

JOptionPaneshowMessageDialog(this, "白棋胜利");

Clear_Chess();

return;

}

}

else

{

white_count = 0;

}

}

}

}

for(i = 4;i < 11;i++)//右向左斜判断

{

for(int j = 6;j >= 0;j--)

{

for(int k = 0;k < 5;k++)

{

if(chess[i - k][j + k] == 1)

{

black_count++;

if(black_count == 5)

{

JOptionPaneshowMessageDialog(this, "黑棋胜利");

Clear_Chess();

return;

}

}

else

{

black_count = 0;

}

if(chess[i - k][j + k] == 2)

{

white_count++;

if(white_count == 5)

{

JOptionPaneshowMessageDialog(this, "白棋胜利");

Clear_Chess();

return;

}

}

else

{

white_count = 0;

}

}

}

}

}

void Clear_Chess()

{

for(int i=0;i<11;i++)

{

for(int j=0;j<11;j++)

{

chess[i][j]=0;

}

}

repaint();

}

public void paint(Graphics g)

{

Drawline(g);

Drawchess(g);

}

public void mouseExited(MouseEvent e){}

public void mouseEntered(MouseEvent e){}

public void mouseReleased(MouseEvent e){}

public void mouseClicked(MouseEvent e){}

}

class myframe extends Frame implements WindowListener

{

mypanel panel;

myframe()

{

setLayout(null);

panel = new mypanel();

add(panel);

panelsetBounds(0,23, 360, 360);

setTitle("单人版五子棋");

setBounds(200, 200, 360, 383);

setVisible(true);

addWindowListener(this);

}

public void windowClosing(WindowEvent e)

{

Systemexit(0);

}

public void windowDeactivated(WindowEvent e){}

public void windowActivated(WindowEvent e){}

public void windowOpened(WindowEvent e){}

public void windowClosed(WindowEvent e){}

public void windowIconified(WindowEvent e){}

public void windowDeiconified(WindowEvent e){}

}

public class mywindow

{

public static void main(String argc [])

{

myframe f = new myframe();

}

}

一:19×19的棋盘

二:能判断输赢

三:最好是人机对战的

如下部分程序:

import javaawt;

import javaawtevent;

class wuziqi

{

public static void main(String args[])

{

new frame();

}

}

class frame extends Frame

{

frame()

{

super("五子棋游戏");

myCanvas canvas=new myCanvas();

thisadd(canvas);

thisaddWindowListener(new WindowAdapter()

{

public void windowClosing(WindowEvent e)

{

Systemexit(0);

}

}

);

thispack();

thisshow();

}

}

class myCanvas extends Canvas

{

myCanvas()

{

}

public void paint(Graphics g)

{

Dimension size=thisgetSize();

gdrawRect(0,0,sizewidth-1,sizeheight-1);

gsetColor(ColorlightGray);

gdraw3DRect(1,1,sizewidth-3,sizeheight-3,true);

gsetColor(Colorblack);

for(int i=0;i<19;i++)

{

gdrawLine(30,30+i24,462,30+i24);

}

for(int j=0;j<19;j++)

{

gdrawLine(30+j24,30,30+j24,462);

}

}

public Dimension getPreferredSize()

{

return new Dimension(492,492);

}

}

// My car shopjava

import javaawt;

import javaawtevent;

import javaxswing;

import javaxswingborder;

public class carshop extends JFrame

{

// JPanel to hold all pictures

private JPanel windowJPanel;

private String[] cars = { "","阿斯顿马丁", "美洲虎", "凯迪拉克",

"罗孚", "劳斯莱斯","别克"};

private int[] jiage = { 0,150000, 260000, 230000,

140000, 290000, 150000};

// JLabels for first snack shown

private JLabel oneJLabel;

private JLabel oneIconJLabel;

// JLabels for second snack shown

private JLabel twoJLabel;

private JLabel twoIconJLabel;

// JLabels for third snack shown

private JLabel threeJLabel;

private JLabel threeIconJLabel;

// JLabels for fourth snack shown

private JLabel fourJLabel;

private JLabel fourIconJLabel;

// JLabels for fifth snack shown

private JLabel fiveJLabel;

private JLabel fiveIconJLabel;

// JLabels for sixth snack shown

private JLabel sixJLabel;

private JLabel sixIconJLabel;

// JTextField for displaying snack price

private JTextArea displayJTextArea;

// JLabel and JTextField for user input

private JLabel inputJLabel;

private JComboBox selectCountryJComboBox;

private JLabel inputJLabel2;

private JTextField inputJTextField2;

// JButton to enter user input

private JButton enterJButton;

//JButton to clear the components

private JButton clearJButton;

// no-argument constructor

public carshop()

{

createUserInterface();

}

// create and position GUI components; register event handlers

private void createUserInterface()

{

// get content pane for attaching GUI components

Container contentPane = getContentPane();

// enable explicit positioning of GUI components

contentPanesetLayout( null );

// set up windowJPanel

windowJPanel = new JPanel();

windowJPanelsetBounds( 10, 20, 340, 200 );

windowJPanelsetBorder( new LineBorder( ColorBLACK ) );

windowJPanelsetLayout( null );

contentPaneadd( windowJPanel );

// set up oneIconJLabel

oneIconJLabel = new JLabel();

oneIconJLabelsetBounds( 10, 20, 100, 65 );

oneIconJLabelsetIcon( new ImageIcon( "images/阿斯顿马丁jpg" ) );

windowJPaneladd( oneIconJLabel );

// set up oneJLabel

oneJLabel = new JLabel();

oneJLabelsetBounds( 10, 60, 100, 70 );

oneJLabelsetText( "阿斯顿马丁" );

oneJLabelsetHorizontalAlignment( JLabelCENTER );

windowJPaneladd( oneJLabel );

// set up twoIconJLabel

twoIconJLabel = new JLabel();

twoIconJLabelsetBounds( 120, 20, 100, 65 );

twoIconJLabelsetIcon( new ImageIcon( "images/美洲虎jpg" ) );

windowJPaneladd( twoIconJLabel );

// set up twoJLabel

twoJLabel = new JLabel();

twoJLabelsetBounds( 110, 60, 100, 70 );

twoJLabelsetText( "美洲虎" );

twoJLabelsetHorizontalAlignment( JLabelCENTER );

windowJPaneladd( twoJLabel );

// set up threeIconJLabel

threeIconJLabel = new JLabel();

threeIconJLabelsetBounds( 230, 20, 100, 65 );

threeIconJLabelsetIcon( new ImageIcon(

"images/凯迪拉克jpg" ) );

windowJPaneladd( threeIconJLabel );

// set up threeJLabel

threeJLabel = new JLabel();

threeJLabelsetBounds( 230, 60, 100, 70);

threeJLabelsetText( "凯迪拉克" );

threeJLabelsetHorizontalAlignment( JLabelCENTER );

windowJPaneladd( threeJLabel );

// set up fourIconJLabel

fourIconJLabel = new JLabel();

fourIconJLabelsetBounds( 10, 100, 100, 65 );

fourIconJLabelsetIcon( new ImageIcon( "images/罗孚jpg" ) );

windowJPaneladd( fourIconJLabel );

// set up fourJLabel

fourJLabel = new JLabel();

fourJLabelsetBounds( 10, 150, 50, 70 );

fourJLabelsetText( "罗孚" );

fourJLabelsetHorizontalAlignment( JLabelCENTER );

windowJPaneladd( fourJLabel );

// set up fiveIconJLabel

fiveIconJLabel = new JLabel();

fiveIconJLabelsetBounds( 120, 100, 100, 65 );

fiveIconJLabelsetIcon( new ImageIcon(

"images/劳斯莱斯jpg" ) );

windowJPaneladd( fiveIconJLabel );

// set up fiveJLabel

fiveJLabel = new JLabel();

fiveJLabelsetBounds( 110, 150, 100, 70 );

fiveJLabelsetText( "劳斯莱斯" );

fiveJLabelsetHorizontalAlignment( JLabelCENTER );

windowJPaneladd( fiveJLabel );

// set up sixIconJLabel

sixIconJLabel = new JLabel();

sixIconJLabelsetBounds( 230, 100, 100, 65 );

sixIconJLabelsetIcon( new ImageIcon( "images/别克jpg" ) );

windowJPaneladd( sixIconJLabel );

// set up sixJLabel

sixJLabel = new JLabel();

sixJLabelsetBounds( 230, 150, 100, 70 );

sixJLabelsetText( "别克" );

sixJLabelsetHorizontalAlignment( JLabelCENTER );

windowJPaneladd( sixJLabel );

// set up enterJButton

enterJButton = new JButton();

enterJButtonsetBounds( 390, 160, 135, 30 );

enterJButtonsetText( "Enter" );

contentPaneadd( enterJButton );

enterJButtonaddActionListener(

new ActionListener() // anonymous inner class

{

// event handler called when enterJButton is clicked

public void actionPerformed( ActionEvent event )

{

enterJButtonActionPerformed( event );

}

} // end anonymous inner class

); // end call to addActionListener

// set up clearJButton

clearJButton = new JButton();

clearJButtonsetBounds( 390, 200, 135, 30 );

clearJButtonsetText( "Clear" );

contentPaneadd( clearJButton );

// set up inputJLabel

inputJLabel = new JLabel();

inputJLabelsetBounds( 390, 25, 135, 25 );

inputJLabelsetText( "Please make selection:" );

contentPaneadd( inputJLabel );

selectCountryJComboBox = new JComboBox( cars );

selectCountryJComboBoxsetBounds( 390, 50, 135, 21 );

selectCountryJComboBoxsetMaximumRowCount( 3 );

contentPaneadd( selectCountryJComboBox );

// set up inputJTextField

inputJLabel2 = new JLabel();

inputJLabel2setBounds( 390, 80, 150, 20 );

inputJLabel2setText( "Input the Numble:" );

contentPaneadd( inputJLabel2 );

// set up inputJTextField

inputJTextField2 = new JTextField();

inputJTextField2setBounds( 390, 100, 135, 25 );

inputJTextField2setHorizontalAlignment( JTextFieldRIGHT );

contentPaneadd( inputJTextField2 );

clearJButtonaddActionListener(

new ActionListener() // anonymous inner class

{

// event handler called when clearJButton is clicked

public void actionPerformed( ActionEvent event )

{

clearJButtonActionPerformed( event );

}

} // end anonymous inner class

);

// set up displayJTextField

displayJTextArea = new JTextArea();

displayJTextAreasetBounds( 10, 237,515, 70 );

displayJTextAreasetEditable( false );

contentPaneadd( displayJTextArea );

// set properties of application's window

setTitle( "My car Shop" ); // set title bar string

setSize( 550, 360 ); // set window size

setVisible( true ); // display window

} // end method createUserInterface

private void clearJButtonActionPerformed( ActionEvent event )

{

// clear the JTextFields

inputJTextField2setText( "" );

displayJTextAreasetText("");

} // end method clearJButtonActionPerformed

private void enterJButtonActionPerformed( ActionEvent event )

{

double z;

double c;

int x;

int y;

x=selectCountryJComboBoxgetSelectedIndex();

y=IntegerparseInt(inputJTextField2getText());

double discountRate;

int amount = IntegerparseInt( inputJTextField2getText());

switch (amount/5)

{

case 0:

discountRate = 0;

break;

case 1:

discountRate = 1;

break;

case 2:

discountRate = 2;

break;

case 3:

discountRate = 3;

break;

default:

discountRate = 4;

} // end switch statement

c=1-discountRate/100;

z=jiage[x]yc;

displayJTextAreaappend("你选择的是:"+cars[x]+";"+

"它的单价是:"+jiage[x]+";" +"你购买该产品的数量是:"+y+"," +"\n"+"该数量的折扣是:"

+discountRate + " %"+";"+"本次消费的总价格是:"+z+"元"+"!"+"\n");

}

public static void main( String args[] )

{

carshop application = new carshop();

applicationsetDefaultCloseOperation( JFrameEXIT_ON_CLOSE );

} // end method main

} // end class carshop

也不知道你具体需求是什么,以前改过一个日历程序,一共四个java类,放在同一个包里。经测试可以运行。

//Startjava

import javaawt;

import javaxswing;

class Start{

public static void main(String [] args){

DateFrame frame=new DateFrame();

framesetLocationRelativeTo(frame);

framesetResizable(false);

framesetDefaultCloseOperation(JFrameEXIT_ON_CLOSE);

framesetVisible(true);

}

}

//DateInfojava

import javautil;

public class DateInfo{

private int mYear, mMonth;

private int mDayOfMonth, mFristWeek;

public DateInfo(int year, int month) throws DateException{

mYear = year;

if (month < 0 || month > 12){

throw (new DateException());

}

mMonth = month;

mDayOfMonth = getDayOfMonth(mYear, mMonth);

mFristWeek = getFristWeek(mYear, mMonth);

}

private int getDayOfMonth(int year, int month){

int[][] ary = {{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},

{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}};

return (ary[isLeapYear(year)][month]);

}

private int isLeapYear(int year){

if (year % 4 == 0 && year % 100 != 0 ||year % 400 == 0){

return (1);

}

else{

return (0);

}

}

private int getFristWeek(int year, int month){

javautilCalendar cal = CalendargetInstance();

calset(year, month - 1, 1);

return (calget(CalendarDAY_OF_WEEK) - 1);

}

public String toString(){

String str;

str = "\t\t" + mYear + "年" + mMonth + "月\n";

str += "日\t一\t二\t三\t四\t五\t六\n";

int i;

for (i = 1; i <= mFristWeek; i++){

str += " \t";

}

for (int j = 1; j <= mDayOfMonth; j++, i++){

str +=j+"\t" ;

if (i % 7 == 0){

str += "\n";

}

}

return (str);

}

}

//DateFramejava

import javaawt;

import javaawtevent;

import javaxswing;

import javautilCalendar;

class DateFrame extends JFrame implements Runnable{

Calendar date=CalendargetInstance();

String[] str={"1","2","3","4","5","6","7","8","9","10","11","12"};

JLabel lblYear=new JLabel("年 ");

JLabel lblMonth=new JLabel("月 ");

JLabel lblDate=new JLabel("现在的时间是:");

JLabel lblShowDate=new JLabel();

// javaxswingJTextField trxt =new JTextField(10);

// trxtsetHorizontalAlignment(JTextFieldRIGHT); //设置文本从右边输入

JComboBox cboMonth=new JComboBox(str);

JComboBox cboYear=new JComboBox();

JTextArea txaShow=new JTextArea();

JPanel pnlNorth=new JPanel();

JPanel pnlSOUTH=new JPanel();

JButton btnShow=new JButton("显示");

JButton btnClose=new JButton("关闭");

JScrollPane jsp=new JScrollPane(txaShow);

Container c=thisgetContentPane();

public DateFrame(){

Thread thread=new Thread(this);

threadstart();

thissetTitle("玩玩日历拉!!!");

thissetSize(300,260);

for (int i = 1990; i<=2025; i++) {

cboYearaddItem(""+i);

}

cboYearsetSelectedItem(""+(dateget(CalendarYEAR)));

cboMonthsetSelectedItem(""+(dateget(CalendarMONTH)+1));

pnlNorthadd(cboYear);

txaShowsetTabSize(4); //设置tab键的距离

txaShowsetForeground(ColorGREEN);

pnlNorthadd(lblYear);

pnlNorthadd(cboMonth);

pnlNorthadd(lblMonth);

pnlNorthadd(lblDate);

pnlNorthadd(lblShowDate);

cadd(pnlNorth,BorderLayoutNORTH);

cadd(jsp);

pnlSOUTHadd(btnShow);

pnlSOUTHadd(btnClose);

cadd(pnlSOUTH,BorderLayoutSOUTH);

btnShowaddActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

int year=IntegerparseInt((String)cboYeargetSelectedItem());

int month=IntegerparseInt((String)cboMonthgetSelectedItem());

try {

DateInfo date=new DateInfo(year,month);

txaShowsetText(""+date);

}

catch (DateException ex) {

exprintStackTrace();

}

}

});

btnCloseaddActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

Systemexit(0);

}

});

}

public void run(){

try {

while(true){

Threadsleep(1000);

int hour=dateget(CalendarHOUR);

int minute=dateget(CalendarMINUTE);

int second=dateget(CalendarSECOND);

String str=hour+":"+minute+":"+second;

lblShowDatesetText(str);

//thisrepaint();

}

}

catch (Exception ex) {

exprintStackTrace();

}

}

}

//DateExceptionjava

public class DateException extends Exception{

public DateException(){

super("日期数据不合法");

}

}

import javaioByteArrayInputStream;

import javaioByteArrayOutputStream;

import javaioFile;

import javaioInputStream;

import orgeclipseswtSWT;

import orgeclipseswtwidgets;

import orgeclipseswtevents;

import javaxsoundsampledAudioFileFormat;

import javaxsoundsampledAudioFormat;

import javaxsoundsampledAudioInputStream;

import javaxsoundsampledAudioSystem;

import javaxsoundsampledDataLine;

import javaxsoundsampledSourceDataLine;

import javaxsoundsampledTargetDataLine;

public class RecordPlay {

boolean stopCapture = false; // 控制录音标志

AudioFormat audioFormat; // 录音格式

// 读取数据:从TargetDataLine写入ByteArrayOutputStream录音

ByteArrayOutputStream byteArrayOutputStream;

int totaldatasize = 0;

TargetDataLine targetDataLine;

// 播放数据:从AudioInputStream写入SourceDataLine播放

AudioInputStream audioInputStream;

SourceDataLine sourceDataLine;

private Button captureBtn;

private Button stopBtn;

private Button playBtn;

private Button saveBtn;

private Label myLabel;

private Shell shell;

private Display display;

public RecordPlay() {

super();

display = new Display();

shell = new Shell(display);

shellsetSize(350, 150);

shellsetText("录音机程序");

//

myLabel = new Label(shell, SWTNONE);

myLabelsetBounds(38, 21, 100, 18);

myLabelsetText("录音机");

// 创建按钮

captureBtn = new Button(shell, SWTNONE);

captureBtnsetBounds(30, 61, 60, 18);

captureBtnsetText("录音");

captureBtnsetEnabled(true);

stopBtn = new Button(shell, SWTNONE);

stopBtnsetBounds(100, 61, 60, 18);

stopBtnsetText("停止");

stopBtnsetEnabled(false);

playBtn = new Button(shell, SWTNONE);

playBtnsetBounds(170, 61, 60, 18);

playBtnsetText("播放");

playBtnsetEnabled(false);

saveBtn = new Button(shell, SWTNONE);

saveBtnsetBounds(240, 61, 60, 18);

saveBtnsetText("保存");

saveBtnsetEnabled(false);

// 注册录音事件

captureBtnaddSelectionListener(new SelectionListener() {

public void widgetSelected(SelectionEvent event) {

captureBtnsetEnabled(false);

stopBtnsetEnabled(true);

playBtnsetEnabled(false);

saveBtnsetEnabled(false);

// 开始录音

capture();

}

public void widgetDefaultSelected(SelectionEvent event) {

// textsetText("No worries!");

}

});

// 注册停止事件

stopBtnaddSelectionListener(new SelectionListener() {

public void widgetSelected(SelectionEvent event) {

captureBtnsetEnabled(true);

stopBtnsetEnabled(false);

playBtnsetEnabled(true);

saveBtnsetEnabled(true);

// 停止录音

stop();

}

public void widgetDefaultSelected(SelectionEvent event) {

// textsetText("No worries!");

}

});

// 注册播放事件

playBtnaddSelectionListener(new SelectionListener() {

public void widgetSelected(SelectionEvent event) {

// 播放录音

play();

}

public void widgetDefaultSelected(SelectionEvent event) {

// textsetText("No worries!");

}

});

// 注册保存事件

saveBtnaddSelectionListener(new SelectionListener() {

public void widgetSelected(SelectionEvent event) {

// 保存录音

save();

}

public void widgetDefaultSelected(SelectionEvent event) {

// textsetText("No worries!");

}

});

}

public void start() {

shellopen();

while (!shellisDisposed()) {

if (!displayreadAndDispatch()) {

displaysleep();

}

}

}

public static void main(String[] args) {

RecordPlay label = new RecordPlay();

labelstart();

}

// (1)录音事件,保存到ByteArrayOutputStream中

private void capture() {

try {

// 打开录音

audioFormat = getAudioFormat();

DataLineInfo dataLineInfo = new DataLineInfo(

TargetDataLineclass, audioFormat);

targetDataLine = (TargetDataLine) AudioSystemgetLine(dataLineInfo);

targetDataLineopen(audioFormat);

targetDataLinestart();

// 创建独立线程进行录音

Thread captureThread = new Thread(new CaptureThread());

captureThreadstart();

} catch (Exception e) {

eprintStackTrace();

Systemexit(0);

}

}

// (2)播放ByteArrayOutputStream中的数据

private void play() {

try {

// 取得录音数据

byte audioData[] = byteArrayOutputStreamtoByteArray();

// 转换成输入流

InputStream byteArrayInputStream = new ByteArrayInputStream(

audioData);

AudioFormat audioFormat = getAudioFormat();

audioInputStream = new AudioInputStream(byteArrayInputStream,

audioFormat, audioDatalength / audioFormatgetFrameSize());

DataLineInfo dataLineInfo = new DataLineInfo(

SourceDataLineclass, audioFormat);

sourceDataLine = (SourceDataLine) AudioSystemgetLine(dataLineInfo);

sourceDataLineopen(audioFormat);

sourceDataLinestart();

// 创建独立线程进行播放

Thread playThread = new Thread(new PlayThread());

playThreadstart();

} catch (Exception e) {

eprintStackTrace();

Systemexit(0);

}

}

// (3)停止录音

public void stop() {

stopCapture = true;

}

// (4)保存文件

public void save() {

// 取得录音输入流

AudioFormat audioFormat = getAudioFormat();

byte audioData[] = byteArrayOutputStreamtoByteArray();

InputStream byteArrayInputStream = new ByteArrayInputStream(audioData);

audioInputStream = new AudioInputStream(byteArrayInputStream,

audioFormat, audioDatalength / audioFormatgetFrameSize());

// 写入文件

try {

File file = new File("d:/myjava/testwav");

AudioSystem

write(audioInputStream, AudioFileFormatTypeWAVE, file);

} catch (Exception e) {

eprintStackTrace();

}

}

// 取得AudioFormat

private AudioFormat getAudioFormat() {

float sampleRate = 160000F;

// 8000,11025,16000,22050,44100

int sampleSizeInBits = 16;

// 8,16

int channels = 1;

// 1,2

boolean signed = true;

// true,false

boolean bigEndian = false;

// true,false

return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed,

bigEndian);

}

class PlayThread extends Thread {

byte tempBuffer[] = new byte[10000];

public void run() {

try {

int cnt;

// 读取数据到缓存数据

while ((cnt = audioInputStreamread(tempBuffer, 0,

tempBufferlength)) != -1) {

if (cnt > 0) {

// 写入缓存数据

sourceDataLinewrite(tempBuffer, 0, cnt);

}

}

// Block等待临时数据被输出为空

sourceDataLinedrain();

sourceDataLineclose();

} catch (Exception e) {

eprintStackTrace();

Systemexit(0);

}

}

}

class CaptureThread extends Thread {

// 临时数组

byte tempBuffer[] = new byte[10000];

public void run() {

byteArrayOutputStream = new ByteArrayOutputStream();

totaldatasize = 0;

stopCapture = false;

try {// 循环执行,直到按下停止录音按钮

while (!stopCapture) {

// 读取10000个数据

int cnt = targetDataLineread(tempBuffer, 0,

tempBufferlength);

if (cnt > 0) {

// 保存该数据

byteArrayOutputStreamwrite(tempBuffer, 0, cnt);

totaldatasize += cnt;

}

}

byteArrayOutputStreamclose();

} catch (Exception e) {

eprintStackTrace();

Systemexit(0);

}

}

}

}

以上就是关于用JAVA编写一个小应用程序全部的内容,包括:用JAVA编写一个小应用程序、怎么写五子棋小程序、java小程序源代码,简单点的,100多行,谁有啊等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zz/9768475.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-01
下一篇 2023-05-01

发表评论

登录后才能评论

评论列表(0条)

保存