java编写一个“猜数”程序:该程序随机在1到1000的范围中选择一个供用户猜测的整数
发布网友
发布时间:2022-05-26 21:29
我来回答
共1个回答
热心网友
时间:2023-11-03 19:19
Java源程序附后。
本程序的特点是:
(1) 文本框只能输入纯数字;
(2) 界面较美观;
(3) 代码可读性较好,有适当的注释;
(4) 窗体一出现就在桌面居中。
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class GuessNumber {
private static final long serialVersionUID = 1L;
JFrame frame;
JTextField txtNum;//文本框
JButton btnStart;//按钮
JLabel lblPrompt;
JLabel lblMessage;
static int source = 0;
static Random rand = new Random();
public GuessNumber(){
frame = new JFrame("Guess Number");
JPanel pnl1, pnl2, pnl3, pnl4;
pnl1 = new JPanel();
pnl1.setLayout(new FlowLayout(FlowLayout.LEFT));
pnl2 = new JPanel();
pnl2.setLayout(new FlowLayout(FlowLayout.LEFT));
pnl3 = new JPanel();
pnl3.setLayout(new FlowLayout(FlowLayout.LEFT));
pnl4 = new JPanel();
pnl4.setLayout(new FlowLayout(FlowLayout.LEFT));
txtNum = new JTextField(10);
btnStart = new JButton("开始");
lblPrompt = new JLabel("<html><body>I have a number between 1 and 1000 can you guess my number?<br/>Please enter your first guess.</body></html>");
lblMessage = new JLabel();
pnl1.add(lblPrompt);
pnl2.add(txtNum);
pnl3.add(lblMessage);
pnl4.add(btnStart);
frame.setLayout(new GridLayout(4, 1));
frame.add(pnl1);
frame.add(pnl2);
frame.add(pnl3);
frame.add(pnl4);
txtNum.addActionListener(this.new TextAction());
txtNum.addKeyListener(this.new KeyAction());
btnStart.addActionListener(this.new ButtonAction());
frame.setSize(400, 200);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
}
public static void main(String[] args) {
new GuessNumber();
while((source=rand.nextInt(1000))==0);
}
//按钮单击后的事件处理
class ButtonAction implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton)e.getSource();
if(btn == btnStart){
while((source=rand.nextInt(1000))==0);
txtNum.setEditable(true);
}
}
}
//文本框按回车后的事件处理
class TextAction implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
JTextField txt = (JTextField)e.getSource();
if(txt != txtNum){
return;
}
int num = Integer.parseInt(txtNum.getText());
if(num == source){
lblMessage.setText("Correct!");
txtNum.setEditable(false);
txtNum.setBackground(frame.getBackground());
}
else if(num > source){
lblMessage.setText("Too High");
txtNum.setBackground(Color.red);
}
else{
lblMessage.setText("Too Low");
txtNum.setBackground(Color.blue);
}
}
}
//*文本框只能输入数字
class KeyAction implements KeyListener{
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
int k = e.getKeyChar();
String text = ((JTextField)e.getSource()).getText();
if(!((k>47 && k <58) || (k==8 || k==KeyEvent.VK_PERIOD))){//*只能输入数字
e.setKeyChar((char)KeyEvent.VK_CLEAR);
}
if(text.length() > 4){//*数值的长度
e.setKeyChar((char)KeyEvent.VK_CLEAR);
}
}
}
}