46
社区成员




import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; public class GuessNumGame{ public static void main(String[] args){ GuessNumGame guessNumGame = new GuessNumGame(); guessNumGame.init(); } JTextField text=new JTextField(20); JLabel label=new JLabel("请输入1-100之间数字!"); Random a = new Random(); int random = a.nextInt(101); public void init() { JFrame f=new JFrame(); JPanel p=new JPanel(); JButton btn=new JButton("我猜!"); //创建内部类 GuessListener guessListener = new GuessListener(); //创建事件监听 btn.addActionListener(guessListener); p.add(text); p.add(btn); p.add(label); f.add(p); f.setTitle("猜数字游戏"); f.setSize(600, 600); f.setLocation(600, 200); f.setVisible(true); f.setResizable(false); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public class GuessListener implements ActionListener{ public void actionPerformed(ActionEvent e) { //获取文本输入框内容 String input=text.getText(); //字符串转int int num=Integer.parseInt(input); System.out.print(random); //判断大小 if(num<random) label.setText("猜小了!"); else if(num>random) label.setText("猜大了!"); else label.setText("猜对啦!"); } } }