java猜数字游戏窗口化
时间: 2023-09-28 11:05:36 浏览: 39
好的,我可以为您提供一个简单的Java猜数字游戏的窗口化程序。下面是代码示例:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GuessingGame extends JFrame implements ActionListener {
private JTextField textField;
private JLabel guessLabel, resultLabel;
private JButton guessButton, playAgainButton;
private int randomNumber;
public GuessingGame() {
setTitle("Guessing Game");
setLayout(new FlowLayout());
guessLabel = new JLabel("Enter your guess between 1 and 100: ");
add(guessLabel);
textField = new JTextField(10);
add(textField);
guessButton = new JButton("Guess");
guessButton.addActionListener(this);
add(guessButton);
resultLabel = new JLabel("");
add(resultLabel);
playAgainButton = new JButton("Play Again");
playAgainButton.addActionListener(this);
add(playAgainButton);
randomNumber = (int) (Math.random() * 100) + 1;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == guessButton) {
int guess = Integer.parseInt(textField.getText());
if (guess == randomNumber) {
resultLabel.setText("Congratulations! You guessed the number!");
} else if (guess < randomNumber) {
resultLabel.setText("Your guess is too low. Try again.");
} else {
resultLabel.setText("Your guess is too high. Try again.");
}
} else if (e.getSource() == playAgainButton) {
randomNumber = (int) (Math.random() * 100) + 1;
resultLabel.setText("");
textField.setText("");
}
}
public static void main(String[] args) {
GuessingGame game = new GuessingGame();
}
}
```
这个程序创建了一个窗口,其中包括一个文本框、两个标签和两个按钮。当用户点击“Guess”按钮时,程序将读取文本框中的输入,将其与随机生成的数字进行比较,并相应地更新结果标签。当用户点击“Play Again”按钮时,程序将生成一个新的随机数,并将结果标签和文本框重置。
希望这个示例能够帮助您开始编写自己的Java窗口化猜数字游戏!