import java.awt.*; import java.awt.event.*; //处理用户与GUI交互的数据类型 import javax.swing.*;
public class Probability extends JApplet implements ActionListener{ final int WON = 0, LOST = 1, CONTINUE = 2 ; //ActionListener接口, //final是常数变量,值不能改变 boolean firstRoll = true; int sumOfDice = 0 ; int myPoint = 0; int gameStatus = CONTINUE; JLabel die1Label, die2Label, sumLabel , pointLabel ; //文本的标签 JTextField die1Field, die2Field, sumField, pointField ; //接收键盘输入信息 JButton rollButton; public void init() { Container container = getContentPane(); // getContentPane()初始化container,container可将GUI组件附加到applet的用户界面中 container.setLayout( new FlowLayout()); //setLayout()为applet的用户界面指定布局管理器。 //FlowLayout 是布局管理器, die1Label = new JLabel("Die 1"); container.add(die1Label); die1Field = new JTextField(10); die1Field.setEditable( false );//设置为不可编辑文本筐 container.add(die1Field); die2Label = new JLabel( "Die 2"); container.add( die2Label ); die2Field = new JTextField(10); die2Field.setEditable( false );//设置为不可编辑文本筐 container.add(die2Field); sumLabel = new JLabel("Sum is"); container.add(sumLabel); sumField = new JTextField(10); sumField.setEditable( false ); container.add(sumField); pointLabel = new JLabel("Point is "); container.add(pointLabel); pointField = new JTextField(10); die1Field.setEditable( false ); container.add( pointField ); rollButton = new JButton("郑散子"); rollButton.addActionListener(this); //设置this applet应该监听rollButton发出的事件 container.add(rollButton); //addActionListener()是JButton的方法,用来通知rollButton, } //横pplet(this)能监听动作事件并包含方法,就是注册GUI组件的事件处理程序 public void actionPerformed(ActionEvent actionEvent)//实现接口ActionListener,以声明一个方法 { sumOfDice = rollDice(); //actionPerformed()是事件处理函数 if(firstRoll) { switch(sumOfDice) { case 7: case 11: gameStatus = WON; pointField.setText(""); break; case 2: case 3: case 12: gameStatus = LOST; pointField.setText(""); break; default: gameStatus = CONTINUE; myPoint = sumOfDice; pointField.setText(Integer.toString(myPoint)); firstRoll = false; break; } } else { if(sumOfDice == myPoint) gameStatus = WON; else if(sumOfDice == 7) gameStatus = LOST; } displayMessage(); } public int rollDice() { int die1 = 1 + (int)(Math.random()*6); int die2 = 1 + (int)(Math.random()*6); int sum = die1 + die2; die1Field.setText(Integer.toString(die1));//toString使int的转换为字符 die2Field.setText(Integer.toString(die2)); sumField.setText(Integer.toString(sum)); return sum; } public void displayMessage() { if(gameStatus == CONTINUE) showStatus("再次投散子"); else { if(gameStatus == WON) showStatus("Player Wins.Click Roll Dice to play again");// showStatus是applet的方法,在applet的状态栏上显示字符 else showStatus("Player loses.Click Roll Dice to play again."); firstRoll = true; } }
}
[此贴子已经被作者于2005-9-22 12:55:06编辑过]
----------------解决方案--------------------------------------------------------
你想问什么问题啊?
----------------解决方案--------------------------------------------------------
没有问题
----------------解决方案--------------------------------------------------------