感谢,终于搞定
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.net.*;
import javax.swing.*;
public class CaiSu extends Applet implements ActionListener
{
JButton b1,b2;
JTextField t1;
JLabel l1;
int default1,y1;
static AudioClip ac1,ac2,ac3;
public static void main(String args[])
{
CaiSu kk=new CaiSu();
kk.default1=(int)(Math.random()*100+1);
kk.init();
}
public void init()
{
try{
URL u1=this.getClass().getResource("da.wav");
URL u2=this.getClass().getResource("xiao.wav");
URL u3=this.getClass().getResource("dui.wav");
ac1=Applet.newAudioClip(u1);
ac2=Applet.newAudioClip(u2);
ac3=Applet.newAudioClip(u3);
}catch(Exception e){}
BorderLayout bl=new BorderLayout(5,5);
JFrame hh=new JFrame("猜数游戏");
hh.setLayout(bl);
l1=new JLabel("请在下面的文本框中输入数字");
b1=new JButton("确定");
b2=new JButton("退出");
t1=new JTextField("",20);
Panel p1=new Panel();
Panel p2=new Panel();
b1.addActionListener(this);
b2.addActionListener(this);
hh.addWindowListener(new ko());
p1.add(t1);
p2.add(b1);p2.add(b2);
hh.add(l1,"North");hh.add(p1,"Center");hh.add(p2,"South");
hh.setBackground(Color.blue);
hh.setResizable(false);
hh.setLocation(350,300);
hh.resize(300,150);
ImageIcon i=new ImageIcon("game.gif");
Image im=i.getImage();
hh.setIconImage(im);
hh.show();
}
public void actionPerformed(ActionEvent at)
{
if (at.getSource()==b2)
System.exit(0) ;
if (at.getSource()==b1)
{
try{
y1=Integer.parseInt(t1.getText());// 将字符串转换成int
}catch(Exception e)
{l1.setText("请输入1-100之间的一个数字");return;}
if (y1>default1)
{
l1.setText("大了");
t1.selectAll();
t1.requestFocus(true); //点击按钮后使文本框得到焦点
ac1.play();
}
if (y1<default1)
{
l1.setText("小了");
t1.selectAll();
t1.requestFocus(true); //点击按钮后使文本框得到焦点
ac2.play();
}
if (y1==default1)
{
l1.setText("恭喜你,猜对了");
ac3.play();
}
}
}
}