方法一:
import java.awt.*;
import java.awt.event.*;
public class MyFrame extends Frame implements ActionListener {
int a;
Button b1 = new Button("得到一个随机数");
TextField tf1 = new TextField(10);
TextField tf2 = new TextField(10);
Button b2 = new Button("确定");
public MyFrame(String s ) {
super(s);
setLayout(new FlowLayout());
tf1.setBackground(Color.CYAN);
add(b1);
add(tf1);
add(tf2);
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
setSize(200,200);
setVisible(true);
validate();
}
public void actionPerformed(ActionEvent e)
{
//String s2 =tf2.getText();
int a2 =Integer.parseInt(tf2.getText());
if(e.getSource()==b1)
{
a =(int)((Math.random()*100)+1);
}
else {
if(e.getSource()==b2)
{
if(a>a2)
{
tf1.setText("猜小了");
}
else
{
if(a
{
tf1.setText("猜大了");
}
else
{
tf1.setText("猜对了");
}
}
}
}
}
}
方法二:
namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int tmp = 0;
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = "";
// Random ra=new Random(unchecked((int)DateTime.Now.Ticks));
Random ra = new Random();
tmp = ra.Next(20, 100); //随机取数
}
private void button2_Click(object sender, EventArgs e)
{
if (Convert.ToInt32(textBox1.Text) > tmp)
{
label1.Visible = true;
label1.Text = "高了!";
}
else if (Convert.ToInt32(textBox1.Text) < tmp)
{
label1.Visible = true;
label1.Text = "低了!";
}
else
{
label1.Visible = true;
label1.Text = "恭喜你!答对了!";
}
textBox1.Focus(); //textBox1获得焦点
}
private void textBox1_TextChanged(object sender, EventArgs e) { label1.Visible = false; }