前几天采写了一个:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Main extends JFrame {
private JTextField text = null;
private JButton buttonGuess = null;
private JButton buttonStart = null;
private JLabel label = null;
private int number = 0;
public Main() {
super("猜数字小游戏");
text = new JTextField("");
text.setPreferredSize(new Dimension(180, 26));
text.setEditable(false);
label = new JLabel();
label.setPreferredSize(new Dimension(300, 26));
buttonGuess = new JButton("Guess");
buttonGuess.setEnabled(false);
buttonGuess.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
guessNumber();
}
});
buttonStart = new JButton("Start");
buttonStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
gameStart();
}
});
JPanel pane = new JPanel();
getContentPane().add(pane);
pane.add(new JLabel("I have a number between 1 and 1000 can you guess my number?"));
pane.add(new JLabel("Please enter your first guess:"));
pane.add(text);
pane.add(buttonGuess);
pane.add(buttonStart);
pane.add(label);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 200);
setLocationRelativeTo(null);
setVisible(true);
}
private void gameStart(){
number = getRand();
text.setEditable(true);
text.setText("");
buttonGuess.setEnabled(true);
}
private void guessNumber(){
int num = 0;
String numStr = text.getText();
try{
num = Integer.parseInt(numStr);
if(num > 1000 || num < 1){
label.setText("between 1 and 1000");
return;
}
if(number < num){
label.setText("Too High");
text.setBackground(Color.red);
}else if(number > num){
label.setText("Too Low");
text.setBackground(Color.blue);
}else{
label.setText("Correct!");
text.setBackground(Color.white);
text.setEditable(false);
buttonGuess.setEnabled(false);
}
}catch (NumberFormatException e) {
label.setText("Error,Please enter Number!");
}
}
private int getRand(){
Random rand = new Random(new Date().getTime());
return rand.nextInt(1000) + 1;
}
public static void main(String[] args) {
new Main();
}
}