简明现代魔法 -> Java编程语言 -> SWT之路:猜数字游戏
SWT之路:猜数字游戏
2009-10-04
程序运行结果

程序代码
package SWT;
import java.util.Random;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class Guess {
protected Shell shell;
private Text text;
static Label resultShow;
int num_Guess;
static int num_Random;
int count = 1;
/**
* Launch the application.
* @param args
*/
public static void main(String[] args) {
num_Random = randomNumberGenerator();
/*
Random rand = new Random();
num_Random = rand.nextInt(100);
System.out.println(num_Random);
*/
System.out.println(num_Random);
try {
Guess window = new Guess();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Open the window.
*/
public void open() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
protected void createContents() {
shell = new Shell();
shell.setSize(450, 300);
shell.setText("猜数字游戏");
{
Group group = new Group(shell, SWT.NONE);
group.setText("输入数字");
group.setBounds(10, 10, 422, 115);
{
text = new Text(group, SWT.BORDER);
text.setBounds(193, 27, 70, 18);
}
{
Button button = new Button(group, SWT.NONE);
button.setBounds(193, 61, 72, 22);
button.setText("猜一下");
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
num_Guess = Integer.parseInt(text.getText());
tip();
count ++;
}
});
}
{
Label label = new Label(group, SWT.NONE);
label.setBounds(10, 31, 171, 12);
label.setText("请输入一个1-100范围内的整数:");
}
}
{
Group group = new Group(shell, SWT.NONE);
group.setText("结果显示");
group.setBounds(10, 141, 422, 115);
{
resultShow = new Label(group, SWT.NONE);
resultShow.setAlignment(SWT.CENTER);
resultShow.setBounds(10, 52, 402, 53);
resultShow.setText("");
}
}
}
public static int randomNumberGenerator() {
Random rand = new Random();
int i = rand.nextInt(100);
return i;
}
public void tip() {
num_Guess = Integer.parseInt(text.getText());
if (num_Random > num_Guess) {
resultShow.setText("没那么小啦,你猜了 " + count + " 次了哦");
text.setText("");
text.forceFocus();
} else if (num_Random < num_Guess) {
resultShow.setText("没那么大啦,你猜了 " + count + " 次了哦");
text.setText("");
text.forceFocus();
} else if (num_Random == num_Guess) {
resultShow.setText("厉害!猜对了,你总共猜了 " + count + " 次了");
}
}
}
程序编写了两个方法。randomNumberGenerator() 用于产生随机数字,tips() 用于比较用户输入的数字与目标数字,产生提示信息。 在主方法调用randomNumberGenerator()方法时,该调用语句必须在异常捕抓之前。text.forceFocus(); 可以让焦点重新回到输入框。
调用tips()方法在按钮事件中进行,同时只要点一下按钮,计数变量count就自增,实现计数。
