[java]代码库
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Chp13_2 extends JFrame{
private JButton chongwan;
private JTextField field;
private JLabel label1,label2;
private Container container;
private int shuzi = (int)(Math.random()*1000+1);
Chp13_2 (){
super("猜数游戏");
container = getContentPane();
container.setLayout(new FlowLayout());
label1 = new JLabel("给你一个1~1000的随机数请你猜,请输入你猜的数:");
container.add(label1);
field = new JTextField(20);
field.addKeyListener(new KeyListener(){
public void keyPressed(KeyEvent arg0) { }
public void keyReleased(KeyEvent arg0) {
int shuru = Integer.parseInt(field.getText());
if(shuru < shuzi ){
container.setBackground(Color.BLUE);
label2.setText("你猜小了!");
}else if(shuru > shuzi){
container.setBackground(Color.RED);
label2.setText("你猜大了!");
}else if(shuru == shuzi){
container.setBackground(Color.WHITE);
label2.setText("你猜对了!");
field.setEditable(false);
}
}
public void keyTyped(KeyEvent arg0){ }
});
container.add(field);
label2 = new JLabel(" ");
container.add(label2);
chongwan = new JButton("重玩");
chongwan.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
shuzi = (int)(Math.random()*1000+1);
field.setEditable(true);
}
});
container.add(chongwan);
setSize(500,400);
setVisible(true);
}
public static void main(String[] args) {
Chp13_2 application = new Chp13_2();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}